#!/usr/bin/env python3
"""List exit-137 incidents in Docker events JSONL; replay one ID or look up a reused name.

Python 3.8+. Reads one local file; no Docker socket, network, or writes.
"""
import argparse
from datetime import datetime, timezone
import json
import re
import sys

IDENT = re.compile(r"[0-9a-f]{64}")
NAME = re.compile(r"[a-zA-Z0-9][a-zA-Z0-9_.-]{0,254}")
ACTIONS = {"create", "start", "oom", "kill", "die", "stop", "restart", "destroy", "rename"}


def load(path):
    rows = []
    with open(path, "rb") as f:
        limit = 16 * 1024 * 1024
        raw_file = f.read(limit + 1)
        if len(raw_file) > limit:
            raise ValueError("File exceeds 16 MiB; use a shorter event window.")
        for line_no, raw in enumerate(raw_file.splitlines(), 1):
            if not raw.strip():
                continue
            try:
                event = json.loads(raw.decode("utf-8-sig"))
                if not isinstance(event, dict) or not isinstance(event.get("Type"), str):
                    raise ValueError
                if event["Type"] != "container":
                    continue
                action = event["Action"]
                if not isinstance(action, str):
                    raise ValueError
                if action not in ACTIONS:
                    continue
                actor = event["Actor"]
                ident = actor["ID"]
                if not isinstance(ident, str) or not IDENT.fullmatch(ident):
                    raise ValueError
                attrs = actor.get("Attributes", {})
                if attrs is None:
                    attrs = {}
                if not isinstance(attrs, dict):
                    raise ValueError
                ns = event.get("timeNano")
                coarse = ns is None or ns == 0
                if coarse:
                    seconds = event["time"]
                    if type(seconds) is not int or seconds <= 0:
                        raise ValueError
                    ns = seconds * 1_000_000_000
                if type(ns) is not int or not 0 < ns <= 2**63-1:
                    raise ValueError
                # Only identifiers and numeric status fields go to the terminal, never free-form labels.
                name = attrs.get("name", "")
                name = name if isinstance(name, str) and NAME.fullmatch(name) else "(unnamed)"
                code = str(attrs.get("exitCode", ""))
                code = code if re.fullmatch(r"\d{1,3}", code, re.ASCII) and int(code) <= 255 else "?"
                sig = str(attrs.get("signal", ""))
                sig = sig if re.fullmatch(r"(?:[0-9]{1,2}|SIG[A-Z0-9]{1,12})", sig) else "?"
                rows.append((ns, coarse, ident, name, action, code, sig))
            except (AttributeError, KeyError, UnicodeError, ValueError, TypeError) as exc:
                raise ValueError("Line %d is not a supported Docker events JSON record; check the capture." % line_no) from exc
    return rows


def show(rows, ident=None, name=None):
    if ident:
        chosen = [r for r in rows if r[2] == ident]
    elif name:
        chosen = [r for r in rows if r[3] == name]
    else:
        chosen = [r for r in rows if r[4] == "die" and r[5] == "137"]
    if not chosen:
        print("No matching record in this file. Missing history does not exclude an OOM or another kill.")
        return
    print("UTC time | full container ID | recorded name | event")
    # Retain the order in the file. A clock adjustment or same-second timestamps cannot prove causality.
    for ns, coarse, cid, recorded_name, action, code, sig in chosen:
        stamp = datetime.fromtimestamp(ns // 1_000_000_000, timezone.utc).strftime("%Y-%m-%dT%H:%M:%S")
        stamp += ("Z (seconds only)" if coarse else ".%09dZ" % (ns % 1_000_000_000))
        detail = (" exit=" + code if action == "die" else " signal=" + sig if action == "kill" else "")
        print("%s | %s | %s | %s%s" % (stamp, cid, recorded_name, action, detail))
    if ident:
        print("Read each start/die interval separately. A kill signal does not name its sender; an oom event does not name the limiting boundary.")
    elif name:
        print("A name can cover several IDs. Compare their full IDs and times; a later object does not describe the old one.")
    else:
        print("Choose the ID by incident time and name, then use --id with the full 64-character ID.")


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("capture", help="Local JSON Lines output from a bounded docker events capture.")
    selector = ap.add_mutually_exclusive_group()
    selector.add_argument("--id", help="Replay lifecycle records for this exact full container ID.")
    selector.add_argument("--name", help="Show lifecycle records carrying this exact name, including any replacement ID.")
    args = ap.parse_args()
    if args.id is not None and not IDENT.fullmatch(args.id):
        ap.error("--id needs the full 64-character lowercase container ID. A name or short prefix can be ambiguous.")
    if args.name is not None and not NAME.fullmatch(args.name):
        ap.error("--name needs the recorded Docker name, without a leading slash.")
    try:
        show(load(args.capture), args.id, args.name)
    except (OSError, ValueError) as exc:
        print("Cannot replay: %s" % exc, file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
