#!/usr/bin/env python3
"""Reproduce a passing code-focused suite and an expected requirement failure.

This uses the unmodified public Go cache teaching fixture. It runs no Proof
command and does not regenerate its archived MC/DC measurement.
"""
import argparse
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import platform
import subprocess
import tempfile

ROOT = Path(__file__).resolve().parent
FIXTURE = ROOT / "fixture"


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


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", default="rerun-results", help="New or empty output directory")
    args = parser.parse_args()
    output = Path(args.output).resolve()
    if output.exists() and (not output.is_dir() or any(output.iterdir())):
        parser.error("Output must be new or empty; captured records are never overwritten.")
    archived = json.loads((FIXTURE / "evidence/provenance.json").read_text())
    source_hashes = {name: digest(FIXTURE / name) for name in archived["sha256"]}
    if source_hashes != archived["sha256"]:
        raise SystemExit("Fixture source/input hashes differ from the archived basis.")
    output.mkdir(parents=True, exist_ok=True)
    commands = [
        ("independence", ["go", "test", "-count=1", "-v", "./cache"], 0),
        ("requirement", ["go", "test", "-count=1", "-tags", "requirement",
                         "-run", "TestTombstoneIsNotServed", "-v", "./cache"], 1),
    ]
    results = []
    with tempfile.TemporaryDirectory(prefix="proof-go-cache-") as cache:
        env = dict(os.environ, GOTOOLCHAIN="local", GOPROXY="off", GOSUMDB="off", GOCACHE=cache)
        version = subprocess.check_output(["go", "version"], text=True, env=env).strip()
        for name, command, expected_exit in commands:
            run = subprocess.run(command, cwd=FIXTURE, env=env, capture_output=True, text=True)
            (output / (name + "-stdout.txt")).write_text(run.stdout)
            (output / (name + "-stderr.txt")).write_text(run.stderr)
            if run.returncode != expected_exit:
                raise SystemExit("Unexpected exit for " + name + "; inspect captured output.")
            if name == "independence":
                if not all("--- PASS: TestIndependence/" + case in run.stdout for case in "ABCD"):
                    raise SystemExit("Missing passing A-D observations; inspect captured output.")
            else:
                if "a deleted entry must not be served" not in run.stdout:
                    raise SystemExit("Expected requirement failure message is missing.")
            results.append({"id": name, "command": command, "expected_exit": expected_exit,
                            "actual_exit": run.returncode, "stdout": name + "-stdout.txt",
                            "stderr": name + "-stderr.txt"})
    report = {
        "schema": "proof-assurance-chain-teaching-rerun-v1",
        "kind": "actual standalone Go teaching-fixture rerun, not airborne software or a Proof CLI run",
        "executed_at_utc": datetime.now(timezone.utc).isoformat(),
        "go_version": version, "platform": platform.platform(),
        "working_directory": "isolated unmodified fixture/ copy accompanying this runner",
        "environment_overrides": {"GOTOOLCHAIN": "local", "GOPROXY": "off", "GOSUMDB": "off",
                                  "GOCACHE": "fresh temporary cache, removed after execution"},
        "source_sha256": source_hashes,
        "runner_sha256": digest(Path(__file__)),
        "all_source_hashes_match_archive": True,
        "runs": results,
        "observed_contrast": {"ordinary_cases_passed": ["A", "B", "C", "D"],
                              "requirement_case": {"Fresh": True, "Hit": True, "Stale": True, "Deleted": True},
                              "requirement_expected": False, "implementation_returned": True,
                              "failure_message": "a deleted entry must not be served"},
        "archived_mcdc": {"recorded_at_utc": archived["recorded_at_utc"],
                          "proof_version": archived["proof_version"],
                          "report_sha256": digest(FIXTURE / "evidence/mcdc.json"),
                          "public_report": "https://reqproof.com/assets/examples/mcdc-cache/evidence/mcdc.json",
                          "covered_conditions": 3, "condition_count": 3, "runtime_samples": 4,
                          "freshly_measured_by_this_runner": False},
        "status": "teaching contrast reproduced; candidate violates the deleted-entry rule",
        "repair_status": "not implemented or executed",
        "acceptance_status": "no project acceptance or certification decision",
        "limits": ["Only two standalone Go test commands ran; the four A-D cases and one requirement counterexample are bounded.",
                   "No Proof audit or new MC/DC instrumentation ran.",
                   "No airborne target, system safety assessment, approved software level, independence or tool qualification was assessed."],
    }
    (output / "provenance.json").write_text(json.dumps(report, indent=2) + "\n")
    payloads = sorted(p for p in output.iterdir() if p.is_file())
    (output / "SHA256SUMS").write_text("".join(digest(p) + "  " + p.name + "\n" for p in payloads))
    print("Reproduced: A-D passed; deleted-entry requirement failed as expected.")
    print("No new MC/DC measurement, repair, acceptance or certification is claimed.")


if __name__ == "__main__":
    main()
