#!/usr/bin/env python3
"""Capture expected baseline failures, the correction, and two selected mutants.

Exit 0 means that this bounded teaching contrast matched its expected outcomes.
It is not software release acceptance, device validation or a conformity result.
"""
import argparse
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import platform
import subprocess
import sys

ROOT = Path(__file__).resolve().parent


def sha(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.")
    output.mkdir(parents=True, exist_ok=True)
    expected = {
        "baseline": (1, 9, 31, ["T04", "T06", "T07"]),
        "corrected": (0, 12, 41, []),
        "mutant_ties_even": (1, 10, 31, ["T04", "T06"]),
        "mutant_missing_as_zero": (1, 11, 41, ["T07"]),
    }
    reports = []
    environment = dict(os.environ, PYTHONDONTWRITEBYTECODE="1")
    started = datetime.now(timezone.utc).isoformat()
    for name, (exit_code, selected_pass, domain_pass, failed_ids) in expected.items():
        command = [sys.executable, "-B", "fixture/run_cases.py", "--implementation", name]
        proc = subprocess.run(command, cwd=ROOT, env=environment, capture_output=True, text=True)
        (output / (name + "-stdout.json")).write_text(proc.stdout)
        (output / (name + "-stderr.txt")).write_text(proc.stderr)
        if proc.returncode != exit_code:
            raise SystemExit("Unexpected process exit for " + name + "; inspect retained output.")
        report = json.loads(proc.stdout)
        selected = report["campaigns"]["selected_contract_cases"]
        domain = report["campaigns"]["bounded_integer_domain"]
        observed_failures = [row["id"] for row in selected["observations"] if not row["passed"]]
        if not (selected["case_count"] == 12 and domain["case_count"] == 41
                and selected["passed"] == selected_pass and domain["passed"] == domain_pass
                and observed_failures == failed_ids and report["oracle_crosscheck"]["passed"]):
            raise SystemExit("Unexpected teaching result for " + name + "; inspect every observation.")
        reports.append({"implementation": name,
                        "command": command,
                        "portable_command": ["python3", "-B", "fixture/run_cases.py", "--implementation", name],
                        "interpreter_used": sys.version.split()[0],
                        "expected_exit": exit_code, "actual_exit": proc.returncode,
                        "selected_passed": selected_pass, "selected_total": 12,
                        "integer_domain_passed": domain_pass, "integer_domain_total": 41,
                        "failed_selected_case_ids": failed_ids,
                        "stdout": name + "-stdout.json", "stderr": name + "-stderr.txt"})
    inputs = [ROOT / "reproduce.py", *(ROOT / "fixture").glob("*.py"), *(ROOT / "fixture").glob("*.json")]
    provenance = {
        "schema": "proof-iec62304-fictional-display-capture-v1",
        "kind": "new actual execution of an original fictional nonclinical teaching fixture",
        "started_at_utc": started, "completed_at_utc": datetime.now(timezone.utc).isoformat(),
        "python": platform.python_version(), "implementation": platform.python_implementation(),
        "platform": platform.platform(),
        "interpreter": Path(sys.executable).name,
        "working_directory": "extracted teaching-kit root, containing fixture/",
        "environment_overrides": {"PYTHONDONTWRITEBYTECODE": "1"},
        "source_sha256": {str(path.relative_to(ROOT)): sha(path) for path in sorted(inputs)},
        "runs": reports,
        "counting_scope": "Each implementation executes 12 selected contract cases and a separate 41-integer-domain campaign. Selected integer cases overlap that domain; do not call them 53 distinct inputs.",
        "wrapper_status": "expected baseline/mutant failures and corrected passes reproduced",
        "acceptance_status": "no project release, device validation, clinical, regulatory or conformity decision",
        "unperformed": ["real device integration and UI rendering", "risk/classification assessment", "clinical use or performance", "timing/concurrency/stale-data behavior", "Proof audit or coverage measurement", "complete lifecycle and release review"],
    }
    (output / "provenance.json").write_text(json.dumps(provenance, indent=2) + "\n")
    files = sorted(path for path in output.iterdir() if path.is_file())
    (output / "SHA256SUMS").write_text("".join(sha(path) + "  " + path.name + "\n" for path in files))
    print("Expected teaching contrast reproduced: baseline 9/12; corrected 12/12.")
    print("Separate integer-domain results: baseline 31/41; corrected 41/41.")
    print("Two selected mutants fail their expected discriminating cases. No release or conformity decision is made.")


if __name__ == "__main__":
    main()
