#!/usr/bin/env python3
"""Refresh route-proof reports after adding captured savedata."""
from __future__ import annotations

import argparse
import subprocess
import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
PYTHON = Path(sys.executable)

REFRESH_CHAIN = [
    "tools/scan_savedata_slots.py",
    "tools/summarize_save_selector_real_savedata_evidence_gap.py",
    "tools/summarize_route_investigation_queue.py",
    "tools/summarize_route_promotion_gate.py",
    "tools/summarize_strict_source_hotspot_external_review_packet.py",
    "tools/summarize_selected_root_execution_external_proof_packet.py",
    "tools/summarize_current_leaf_wrapper_external_proof_packet.py",
    "tools/summarize_predecessor_fill_external_proof_packet.py",
    "tools/summarize_selector_merge_external_proof_packet.py",
    "tools/summarize_opcode20_gate_base_external_proof_packet.py",
    "tools/summarize_opcode24_runtime_producer_external_proof_packet.py",
    "tools/summarize_completion_audit.py",
    "tools/summarize_route_blocker_evidence_matrix.py",
    "tools/summarize_route_promotion_external_proof_handoff.py",
    "tools/validate_route_promotion_external_proof.py",
    "tools/summarize_goal_completion_checklist.py",
]


def display_command(script: str, args: list[str]) -> str:
    rendered_args = " ".join(args)
    suffix = f" {rendered_args}" if rendered_args else ""
    return f"python3 {script}{suffix}"


def run_step(script: str, args: list[str], dry_run: bool) -> None:
    print(f"+ {display_command(script, args)}", flush=True)
    if dry_run:
        return
    subprocess.run(
        [str(PYTHON), str(ROOT / script), *args],
        cwd=ROOT,
        check=True,
    )


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--search-root",
        type=Path,
        action="append",
        default=[],
        help=(
            "captured savedat*.dat file, zip, or directory to scan; repeatable. "
            "When omitted, the savedata scan uses its default roots."
        ),
    )
    parser.add_argument(
        "--no-verify",
        action="store_true",
        help="skip the final tools/verify_web_assets.py pass",
    )
    parser.add_argument(
        "--proof-json",
        type=Path,
        help=(
            "submitted external proof JSON record/list/wrapper to validate. "
            "When omitted, the validator records the generated template-only blocked state."
        ),
    )
    parser.add_argument(
        "--require-accepted-proof",
        action="store_true",
        help="fail the refresh if --proof-json has no accepted external proof record",
    )
    parser.add_argument(
        "--dry-run",
        action="store_true",
        help="print the refresh commands without running them",
    )
    args = parser.parse_args()

    for script in REFRESH_CHAIN:
        step_args: list[str] = []
        if script.endswith("scan_savedata_slots.py") or script.endswith("summarize_save_selector_real_savedata_evidence_gap.py"):
            for root in args.search_root:
                step_args.extend(["--search-root", str(root)])
        if script.endswith("validate_route_promotion_external_proof.py"):
            if args.proof_json:
                step_args.append(str(args.proof_json))
            if args.require_accepted_proof:
                step_args.append("--require-accepted")
        run_step(script, step_args, args.dry_run)

    if not args.no_verify:
        run_step("tools/verify_web_assets.py", [], args.dry_run)


if __name__ == "__main__":
    main()
