#!/usr/bin/env python3
"""Registers a stuck run in the trace db and blocks until factory stop kills it."""

from __future__ import annotations

import os
import shlex
import signal
import subprocess
import sys
from pathlib import Path

from adw_modules.control import read_proc_start_ticks
from adw_modules.tracer import Tracer


def main() -> None:
    db_path = os.environ["FACTORY_TEST_DB"]
    data_dir = os.environ["FACTORY_DATA_DIR"]
    adw_id = os.environ.get("ADW_ID", "stop-test")
    order_file = Path(os.environ["ORDER_FILE"])
    child_mode = os.environ.get("CHILD_MODE", "normal")
    fixture_dir = Path(__file__).resolve().parent
    child_script = fixture_dir / "stop_child.py"

    order_file.parent.mkdir(parents=True, exist_ok=True)
    order_file.write_text("")

    children: list[subprocess.Popen[str]] = []
    child_meta: list[tuple[str, str, list[str]]] = []
    stdin_handles: list[object] = []

    for token in ("child-a", "child-b"):
        child_argv = [
            sys.executable,
            str(child_script),
            str(order_file),
            token,
            child_mode,
        ]
        proc = subprocess.Popen(
            child_argv,
            stdin=subprocess.PIPE,
            text=True,
        )
        assert proc.stdin is not None
        stdin_handles.append(proc.stdin)
        children.append(proc)
        child_meta.append(("agent", token, child_argv))

    tracer = Tracer(
        db_path,
        f"{data_dir}/sessions/{adw_id}/events.jsonl",
    )
    tracer.session_start(adw_id, "factory-stop-test", adw_name="stop_parent", repo=os.getcwd())

    for proc, (kind, name, child_argv) in zip(children, child_meta, strict=True):
        tracer.process_start(
            adw_id,
            kind,
            name,
            proc.pid,
            shlex.join(child_argv),
            start_ticks=read_proc_start_ticks(proc.pid),
        )

    parent_command = shlex.join(
        [sys.executable, str(Path(sys.argv[0]).resolve()), *sys.argv[1:]],
    )
    tracer.process_start(
        adw_id, "adw", "", os.getpid(), parent_command,
        start_ticks=read_proc_start_ticks(os.getpid()),
    )

    def on_parent_term(_signum, _frame) -> None:
        with open(order_file, "a", encoding="utf-8") as handle:
            handle.write("parent\n")
        raise SystemExit(0)

    signal.signal(signal.SIGTERM, on_parent_term)
    signal.signal(signal.SIGINT, on_parent_term)

    try:
        sys.stdin.read(1)
    except OSError:
        pass


if __name__ == "__main__":
    main()
