#!/usr/bin/env python3
"""Build lab Triple 7's 0x89 synth line (3× TRIPLE7 on payline 1).

Usage:
  python build_triple7s_jpot_synth.py --template-file packets.raw --line 2
  python build_triple7s_jpot_synth.py --template "05,89,01,38,D7,..."
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

from pog422_fixture_core import (
    SLOT_WIRE_TRIPLE7,
    build_triple7s_jpot_synth,
    pog422_frame_checksum_ok,
    slot_grid_wire_from_result,
)


def parse_hex_line(line: str) -> bytes:
    line = line.strip()
    if not line or line.startswith("#"):
        return b""
    return bytes(int(part, 16) for part in line.split(","))


def main() -> int:
    ap = argparse.ArgumentParser(description="Build Triple 7's lab 0x89 jackpot grid synth")
    ap.add_argument("--template", help="comma-separated hex template 0x89 frame")
    ap.add_argument("--template-file", type=Path, help="packets.raw or similar")
    ap.add_argument("--line", type=int, default=1, help="1-based line number in template-file")
    args = ap.parse_args()

    if args.template:
        template = parse_hex_line(args.template)
    elif args.template_file:
        lines = [
            ln.strip()
            for ln in args.template_file.read_text(encoding="utf-8").splitlines()
            if ln.strip() and not ln.startswith("#")
        ]
        if not (1 <= args.line <= len(lines)):
            print(f"line {args.line} out of range (1..{len(lines)})", file=sys.stderr)
            return 1
        template = parse_hex_line(lines[args.line - 1])
    else:
        ap.print_help()
        return 2

    synth = build_triple7s_jpot_synth(template)
    if synth is None:
        print("build_triple7s_jpot_synth failed (need 36 B 0x89 template)", file=sys.stderr)
        return 1
    if not pog422_frame_checksum_ok(synth):
        print("checksum invalid after synth", file=sys.stderr)
        return 1
    grid = slot_grid_wire_from_result(synth)
    if grid is None or grid[3:6] != (SLOT_WIRE_TRIPLE7,) * 3:
        print("payline 1 not TRIPLE7 after synth", file=sys.stderr)
        return 1
    print(",".join(f"{b:02X}" for b in synth))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
