#!/usr/bin/env python3
import argparse
from pathlib import Path

from hil_common import PairCapture, load_config, main_guard, new_artifact_dir, pair_ports


def main() -> int:
    parser = argparse.ArgumentParser(description="Capture both approved serial streams concurrently")
    parser.add_argument("--seconds", type=float)
    parser.add_argument("--artifact-dir")
    parser.add_argument("--reset", action="store_true", help="normally reboot both boards after capture starts")
    parser.add_argument("--fault", choices=["drop_chunk", "duplicate_chunk", "corrupt_chunk", "suppress_ack",
                                                   "delay_ack", "wrong_ack_batch"])
    parser.add_argument("--fault-after", type=float, default=10.0)
    args = parser.parse_args()
    config = load_config()
    ports = pair_ports(config, "access")
    baud = int(config.get("hil", {}).get("baud", 115200))
    seconds = args.seconds or float(config.get("hil", {}).get("capture_seconds", 180))
    artifact = Path(args.artifact_dir) if args.artifact_dir else new_artifact_dir("capture")
    sent = False

    def tick(elapsed: float, capture: PairCapture) -> None:
        nonlocal sent
        if args.fault and not sent and elapsed >= args.fault_after:
            target = "sender" if args.fault.endswith("chunk") else "receiver"
            command = "delay_ack:1000" if args.fault == "delay_ack" else args.fault
            capture.send_fault(target, command)
            sent = True

    PairCapture(ports, baud, artifact).run(seconds, tick, reset_on_start=args.reset)
    print(f"Capture artifacts: {artifact}")
    return 0


if __name__ == "__main__":
    main_guard(main)
