from __future__ import annotations

import hashlib
import json
import tempfile
from pathlib import Path

import numpy as np

from m3m_twin.demo import run_demo


ROOT = Path(__file__).resolve().parent
REPORT = ROOT / "reproducibility-check.json"
BYTE_FILES = (
    "mavic-3m-specification-receipt.json",
    "mission-summary.json",
    "capture-manifest.csv",
    "capture-qc-summary.json",
    "radiometric-processing-receipt.json",
    "system-analysis.json",
    "engineering-demo-receipt.json",
)


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


def main() -> None:
    canonical = ROOT / "outputs" / "demo"
    errors: list[str] = []
    identical: dict[str, str] = {}
    with tempfile.TemporaryDirectory(prefix="shwrp034-repro-") as directory:
        temporary = Path(directory)
        run_demo(ROOT, 20260804, output_root=temporary)
        generated = temporary / "outputs" / "demo"
        for name in BYTE_FILES:
            expected = canonical / name
            actual = generated / name
            if not expected.is_file() or not actual.is_file() or expected.read_bytes() != actual.read_bytes():
                errors.append(f"byte comparison failed: {name}")
            else:
                identical[name] = digest(expected)
        with np.load(canonical / "synthetic-analysis-arrays.npz") as expected_npz, np.load(
            generated / "synthetic-analysis-arrays.npz"
        ) as actual_npz:
            if set(expected_npz.files) != set(actual_npz.files):
                errors.append("NPZ member sets differ")
            else:
                for name in expected_npz.files:
                    if not np.array_equal(expected_npz[name], actual_npz[name], equal_nan=True):
                        errors.append(f"NPZ array differs: {name}")
                if not errors:
                    identical["synthetic-analysis-arrays.npz::arrays"] = "numerically identical for all members"
    payload = {
        "schemaVersion": 1,
        "checkedOn": "2026-08-04",
        "status": "PASSED" if not errors else "FAILED",
        "seed": 20260804,
        "byteIdenticalFiles": identical,
        "claimBoundary": "Reproducibility applies only to the deterministic digital-twin fixture, not to field performance.",
        "errors": errors,
    }
    REPORT.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({"status": payload["status"], "comparisons": len(identical), "errors": len(errors)}, ensure_ascii=False))
    if errors:
        raise SystemExit(1)


if __name__ == "__main__":
    main()
