"""Reproduce green/missing/weak/strong controls; expected failures are required."""

import argparse
import datetime
import hashlib
import json
import os
import platform
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent
RUNS = [
    ("upper-only-existing-three", "upper-only", "existing-three", "literal", 0, 3, 0),
    ("upper-only-original-zero", "upper-only", "original-zero", "literal", 1, 0, 1),
    ("upper-only-weak-six-neighbors", "upper-only", "six-neighbors", "weak-range", 0, 6, 0),
    ("upper-only-selected-nine", "upper-only", "selected-nine", "literal", 1, 7, 2),
    ("corrected-selected-nine", "corrected", "selected-nine", "literal", 0, 9, 0),
    ("constant-one-selected-nine", "constant-one", "selected-nine", "literal", 1, 3, 6),
    ("cap-nineteen-selected-nine", "cap-nineteen", "selected-nine", "literal", 1, 6, 3),
    ("interior-hole-selected-nine", "interior-hole", "selected-nine", "literal", 0, 9, 0),
    ("interior-hole-held-out-seven", "interior-hole", "held-out-seven", "literal", 1, 0, 1),
    ("corrected-held-out-seven", "corrected", "held-out-seven", "literal", 0, 1, 0),
]


def utc_now():
    return datetime.datetime.now(datetime.timezone.utc).isoformat()


def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--output-dir", type=Path, default=ROOT / "rerun-output")
    args = parser.parse_args()
    if not __debug__ or sys.flags.optimize:
        parser.error("Use ordinary Python without -O/PYTHONOPTIMIZE: the unchanged historical snippet uses assert")
    output = args.output_dir.resolve()
    output.mkdir(parents=True, exist_ok=True)
    if any(output.iterdir()):
        parser.error("Output directory must be empty; preserve earlier raw runs")
    started = utc_now()
    hashes = {name: digest(ROOT / name) for name in
              ["clamp.py", "run_cases.py", "reproduce.py", "cases.json", "contract.json",
               "README.md", "historical-snippet.py", "historical-origin.json"]}
    # Compile original bytes with a stable, relative traceback filename. This
    # executes the archived source unchanged, including its actual assert failure.
    historical_command = [sys.executable, "-B", "-u", "-c",
                          "from pathlib import Path; exec(compile(Path('historical-snippet.py').read_text(), 'historical-snippet.py', 'exec'))"]
    historical_started = utc_now()
    child = subprocess.run(historical_command, cwd=ROOT, capture_output=True, check=False)
    (output / "historical-replay.stdout.txt").write_bytes(child.stdout)
    (output / "historical-replay.stderr.txt").write_bytes(child.stderr)
    historical = {"classification": "Fresh replay of retained dated historical snippet; not original 2 October execution evidence.",
                  "command": historical_command, "cwd": ".", "started_utc": historical_started,
                  "finished_utc": utc_now(), "exit_code": child.returncode,
                  "expected_exit_code": 1, "assertions_enabled": True,
                  "source_sha256": hashes["historical-snippet.py"],
                  "expected_observation_reproduced": child.returncode == 1 and
                      child.stdout.decode() == "Existing cases: 3 passed\nBoundary case: requested=0, expected=1, actual=0\n" and
                      b"AssertionError" in child.stderr,
                  "function_invocations": 4}
    (output / "historical-replay.json").write_text(json.dumps(historical, indent=2, sort_keys=True) + "\n")
    runs = []
    for name, implementation, selection, oracle, expected_exit, passed, failed in RUNS:
        command = [sys.executable, "-B", "-u", "run_cases.py", "--implementation", implementation,
                   "--selection", selection, "--oracle", oracle]
        run_started = utc_now()
        child = subprocess.run(command, cwd=ROOT, capture_output=True, check=False)
        (output / (name + ".stdout.json")).write_bytes(child.stdout)
        (output / (name + ".stderr.txt")).write_bytes(child.stderr)
        try:
            report = json.loads(child.stdout)
            counts = report["counts"]
        except (ValueError, KeyError):
            report, counts = {}, {}
        matched = child.returncode == expected_exit and child.stderr == b"" and counts.get("passed") == passed and counts.get("failed") == failed
        runs.append({"name": name, "command": command, "cwd": ".", "started_utc": run_started,
                     "finished_utc": utc_now(), "exit_code": child.returncode,
                     "expected_exit_code": expected_exit, "counts": counts,
                     "expected_observation_reproduced": matched,
                     "implementation_accepted_by_selected_gate": report.get("accepted_by_selected_gate")})
    read = lambda name: json.loads((output / (name + ".stdout.json")).read_text())
    weak = read("upper-only-weak-six-neighbors")
    original = read("upper-only-original-zero")["results"][0]
    baseline = read("upper-only-selected-nine")
    hole = read("interior-hole-held-out-seven")["results"][0]
    checks = {
        "original_zero_is_exact_required_failure": original["requested"] == 0 and original["requirement_expected"] == 1 and original["actual"] == 0,
        "weak_gate_accepts_actual_requirement_mismatch": weak["accepted_by_selected_gate"] and weak["counts"]["requirement_mismatches"] == 1,
        "selected_baseline_fails_only_negative_and_zero": [row["requested"] for row in baseline["results"] if not row["passed"]] == [-1, 0],
        "seeded_held_out_mismatch_is_exact": hole["requested"] == 7 and hole["requirement_expected"] == 7 and hole["actual"] == 8,
    }
    reproduced = historical["expected_observation_reproduced"] and all(run["expected_observation_reproduced"] for run in runs) and all(checks.values())
    summary = {"experiment_reproduced": reproduced,
               "meaning": "Wrapper success requires expected passing AND failing children; it does not accept all implementations or prove class closure.",
               "started_utc": started, "finished_utc": utc_now(), "source_sha256": hashes,
               "runtime": {"python": platform.python_version(), "python_build": sys.version,
                           "executable": sys.executable, "debug_assertions_enabled": __debug__,
                           "optimize_flag": sys.flags.optimize,
                           "PYTHONOPTIMIZE": os.environ.get("PYTHONOPTIMIZE")},
               "historical_fresh_replay": historical, "runs": runs, "sensitivity_checks": checks,
               "counts_and_units": {"unique_requested_integer_values": 10,
                                    "selected_table_cases": 9, "edge_neighbor_cases_within_selected": 6,
                                    "additional_designed_held_out_case": 1,
                                    "structured_gate_runs": len(runs),
                                    "structured_function_invocations": sum(run["counts"].get("function_invocations", 0) for run in runs),
                                    "historical_replay_function_invocations": 4,
                                    "held_out_note": "Designed exclusion from selected-nine, not randomized/statistically independent validation."}}
    (output / "reproduction-summary.json").write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n")
    print(json.dumps(summary, indent=2, sort_keys=True))
    return 0 if reproduced else 1


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