#!/usr/bin/env python3
"""Trace failed JP 0x81 path: pos1 slave -> hub inject to Master."""
from __future__ import annotations

import json
from datetime import datetime
from pathlib import Path

BASE = Path(__file__).resolve().parents[1] / "logs"
T0 = datetime.fromisoformat("2026-08-04T02:29:51.800000+00:00")
T1 = datetime.fromisoformat("2026-08-04T02:29:53.500000+00:00")


def parse(s: str) -> datetime:
    return datetime.fromisoformat(s.replace("Z", "+00:00"))


def dump(pos: int, title: str) -> None:
    print(f"\n======== pos{pos} {title} ========")
    d = BASE / str(pos) / "data"
    for fp in sorted(d.glob("events.jsonl*")):
        with open(fp, encoding="utf-8", errors="replace") as f:
            for line in f:
                if "2026-08-04T02:29:5" not in line:
                    continue
                try:
                    e = json.loads(line)
                except Exception:
                    continue
                t = e.get("utc")
                if not t:
                    continue
                try:
                    tt = parse(t)
                except Exception:
                    continue
                if not (T0 <= tt <= T1):
                    continue
                tid = str(e.get("tid") or "")
                msg = str(e.get("msg") or "")
                ev = e.get("ev") or ""
                sent_tid = str(e.get("sent_tid") or "")
                keep = False
                if tid == "1DAF" or sent_tid == "1DAF" or msg in ("81", "89", "80"):
                    keep = True
                if any(
                    x in ev
                    for x in (
                        "inject",
                        "error",
                        "fail",
                        "eth_tx",
                        "eth_rx",
                        "packet_complete",
                        "uart",
                        "bank_wlan_jackpot",
                        "defer",
                        "marshal",
                        "fanout",
                        "peer_gameplay",
                        "gpio",
                        "slv",
                        "hs_",
                    )
                ):
                    if (
                        tid in ("1DAF", "", "0000")
                        or msg in ("81", "89", "80", "0A", "0D")
                        or sent_tid == "1DAF"
                        or e.get("eth_port") in ("eg-s11",)
                    ):
                        keep = True
                if not keep:
                    continue
                keys = [
                    "utc",
                    "ev",
                    "tid",
                    "game",
                    "msg",
                    "reason",
                    "where",
                    "source",
                    "eth_port",
                    "channel",
                    "play_sequence",
                    "echo_len",
                    "match",
                    "driver_errno",
                    "de_release_reason",
                    "usb_actual",
                    "bus_rx_source",
                    "message",
                    "sent_msg",
                    "sent_tid",
                    "peer_msgs",
                    "queue_wait_us",
                    "inject_path",
                    "air_us",
                    "progwin_cents",
                    "counter",
                    "attempt",
                    "tx_fifo_before",
                    "tx_fifo_after_bulk",
                    "echo_prefix",
                    "marshal_head",
                    "match_kind",
                    "bus_framing_ok",
                    "inject_engine",
                    "slv_hs_idle_at_queue",
                    "stom_comm_priority",
                    "manual_gpio7_slv",
                    "tx_empty_reason_name",
                ]
                out = {k: e.get(k) for k in keys if e.get(k) is not None}
                print(json.dumps(out, separators=(",", ":")))


def main() -> None:
    dump(1, "pos1 EDGE bridge (slave 1DAF)")
    dump(3, "hub Master inject")
    dump(11, "pos1 copper witness")


if __name__ == "__main__":
    main()
