#!/usr/bin/env python3
"""Run four contrasts once each; preserve genuine child exits and captured bytes."""
import argparse
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import platform
import subprocess
import sys
import time

ROOT = Path(__file__).resolve().parent
SOURCES = ("reproduce.py", "fixture/debounce.py", "fixture/oracle.py",
           "fixture/run_traces.py", "fixture/selected-traces.json", "fixture/requirements.md")
# Independently derived with prefix counts, trailing patterns and removal of
# UNKNOWN before matching, rather than implementation counters. These expected
# campaign counts are checks of the demonstration, not extra test executions.
EXPECTED = {
    "baseline": (1, ["T06", "T07", "T08", "T09", "T10"], 825, 268),
    "corrected": (0, [], 1093, 0),
    "off_by_one": (1, ["T04", "T05", "T09", "T10", "T11", "T12"], 985, 108),
    "unknown_pauses": (1, ["T07", "T08", "T10"], 986, 107),
}


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


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


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", type=Path, required=True,
                        help="new output directory; existing directories are refused")
    args = parser.parse_args()
    out = args.output.resolve()
    out.mkdir(parents=True, exist_ok=False)
    started = utc()
    source_hashes = {x: sha(ROOT / x) for x in SOURCES}
    invocations = []
    checks = []
    for name, (expected_exit, failed_ids, enum_pass, enum_fail) in EXPECTED.items():
        destination = out / name
        relative = destination.relative_to(ROOT) if destination.is_relative_to(ROOT) else destination
        command = [sys.executable, "-B", "fixture/run_traces.py", "--implementation", name,
                   "--output", str(relative)]
        begin = utc()
        timer = time.perf_counter()
        result = subprocess.run(command, cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        elapsed = time.perf_counter() - timer
        (out / f"{name}.stdout.txt").write_bytes(result.stdout)
        (out / f"{name}.stderr.txt").write_bytes(result.stderr)
        invocations.append({"implementation": name, "argv": command,
                            "working_directory": ".", "started_at_utc": begin,
                            "ended_at_utc": utc(), "elapsed_seconds": round(elapsed, 6),
                            "exit_code": result.returncode,
                            "expected_exit_code": expected_exit,
                            "stdout_file": f"{name}.stdout.txt", "stderr_file": f"{name}.stderr.txt"})
        try:
            selected = json.loads((destination / "selected-results.json").read_text())
            enumeration = json.loads((destination / "enumeration-summary.json").read_text())
            valid = (result.returncode == expected_exit and not result.stderr
                     and selected["traces"] == 12 and selected["failed_trace_ids"] == failed_ids
                     and selected["passed"] == 12 - len(failed_ids)
                     and enumeration["traces"] == 1093
                     and enumeration["passed"] == enum_pass and enumeration["failed"] == enum_fail)
        except (OSError, ValueError, KeyError):
            valid = False
        checks.append({"implementation": name, "expected_contrast_observed": valid})
    unchanged = source_hashes == {x: sha(ROOT / x) for x in SOURCES}
    all_ok = all(c["expected_contrast_observed"] for c in checks) and unchanged
    artifact_hashes = {str(p.relative_to(out)): sha(p) for p in sorted(out.rglob("*")) if p.is_file()}
    report = {
        "schema": "proof-teaching-fixture-execution-v1", "subject": "fictional sample-sequence debounce rule",
        "started_at_utc": started, "ended_at_utc": utc(),
        "wrapper_argv": [sys.executable, "reproduce.py", "--output", str(args.output)],
        "wrapper_exit_code": 0 if all_ok else 1,
        "wrapper_exit_meaning": "0 means all four expected contrasting outcomes were reproduced and sources stayed unchanged; it does not mean all implementations passed.",
        "runtime": {"python": sys.version, "python_executable": sys.executable,
                    "platform": platform.platform(), "machine": platform.machine(),
                    "external_packages": []},
        "source_sha256": source_hashes, "sources_unchanged_during_execution": unchanged,
        "invocations": invocations, "validation_checks": checks,
        "artifact_sha256_relative_to_capture": artifact_hashes,
        "not_performed": ["Proof audit", "MC/DC or structural coverage measurement", "formal proof",
                          "malformed-input campaign", "sample timing or scheduler measurement",
                          "hardware or target integration", "vehicle safety validation", "ASIL assignment",
                          "tool-confidence classification or qualification"],
        "counting_scope": "12 selected traces and 1093 enumerated traces per implementation, four child executions. Selected traces are a readable overlapping subset. A trace passes only when every flag matches. No claim for arbitrary trace lengths or real time."}
    (out / "execution-report.json").write_text(json.dumps(report, indent=2) + "\n")
    print(json.dumps({"capture": str(args.output), "expected_contrast_reproduced": all_ok,
                      "child_executions": len(invocations), "wrapper_exit_code": report["wrapper_exit_code"]}))
    return report["wrapper_exit_code"]


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