from __future__ import annotations

import hashlib
import json
import os
import subprocess
import sys
import tempfile
from pathlib import Path


ROOT = Path(__file__).resolve().parent
CANONICAL = ROOT / "outputs" / "demo" / "artifacts"
REPORT = ROOT / "reproducibility-check.json"
ARTIFACTS = (
    "model.json",
    "evaluation.json",
    "split-receipt.json",
    "model-card.json",
    "inference-receipt.json",
)


def digest(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def main() -> None:
    errors: list[str] = []
    identical: dict[str, str] = {}
    with tempfile.TemporaryDirectory(prefix="shwrp033-repro-") as temporary:
        output = Path(temporary) / "demo"
        completed = subprocess.run(
            [sys.executable, "-m", "m3m_disease", "demo", "--output", str(output), "--seed", "20260804"],
            cwd=ROOT,
            capture_output=True,
            text=True,
            encoding="utf-8",
            errors="replace",
            timeout=180,
            check=False,
            env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"},
        )
        if completed.returncode != 0:
            errors.append("Isolated demo command failed: " + completed.stderr[-1000:])
        generated = output / "artifacts"
        for name in ARTIFACTS:
            expected = CANONICAL / name
            actual = generated / name
            if not expected.is_file() or not actual.is_file():
                errors.append(f"Missing reproducibility artifact: {name}")
                continue
            expected_hash = digest(expected)
            actual_hash = digest(actual)
            if expected_hash != actual_hash:
                errors.append(f"Byte-for-byte mismatch: {name}")
            else:
                identical[name] = expected_hash

    payload = {
        "schemaVersion": 1,
        "checkedOn": "2026-08-04",
        "status": "PASSED" if not errors else "FAILED",
        "command": "python -m m3m_disease demo --output <isolated-temp> --seed 20260804",
        "comparison": "Byte-for-byte comparison between the canonical demo artifacts and a clean isolated rerun.",
        "identicalArtifacts": identical,
        "claimBoundary": "Deterministic equality establishes software reproducibility for the synthetic fixture only; it is not evidence of field disease validity.",
        "errors": errors,
    }
    REPORT.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({"status": payload["status"], "identical": len(identical), "errors": len(errors)}, ensure_ascii=False))
    if errors:
        raise SystemExit(1)


if __name__ == "__main__":
    main()
