#!/usr/bin/env python3
"""CPU-only, no-clobber rebuild of the six formal-three canonical products."""
from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path
import sys

ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT / "src"))

from OID_analysis.v2.geometry import build_legacy_geometry, crop_stride_metric
from OID_analysis.v2.oid import build_canonical_paired_product, load_canonical_product
from CCD_analysis.utils.run_contract import deterministic_json_bytes

SCENES = ("karman_re100", "illusion_1.0L")
REALIZATIONS = ("r1", "r2", "r3")
CROP = (slice(360, 1000), slice(None))
STRIDE = 8
EXPECTED = {"karman_re100": (5025, 95), "illusion_1.0L": (5024, 96)}


def _content_semantics(kind: str) -> str:
    if kind == "fields":
        return "online.py fields_sha256: SHA-256 over ux then uy; each contributes str(dtype), int64 shape bytes, C-order data bytes"
    return "online.py telemetry_sha256: SHA-256 over concatenated sorted telemetry array_sha256 hex digests"


def _branch_artifacts(run: Path, branch: str) -> dict[str, dict[str, str]]:
    manifest_path = run / branch / "branch.json"
    manifest = json.loads(manifest_path.read_text())
    result = {f"{branch}_manifest": {"path": str(manifest_path)}}
    for kind in ("fields", "telemetry"):
        result[f"{branch}_{kind}"] = {
            "path": str(run / branch / f"{kind}.npz"),
            "declared_content_sha256": manifest[f"{kind}_sha256"],
            "content_hash_semantics": _content_semantics(kind),
        }
    return result


def _canonical_and_evidence(run: Path):
    controlled = _branch_artifacts(run, "controlled")
    zero = _branch_artifacts(run, "zero_baseline")
    twin = _branch_artifacts(run, "baseline_twin")
    sources = {
        "controlled_fields": controlled["controlled_fields"],
        "controlled_telemetry": controlled["controlled_telemetry"],
        "zero_baseline_fields": zero["zero_baseline_fields"],
        "zero_baseline_telemetry": zero["zero_baseline_telemetry"],
    }
    evidence = {**twin, "paired_collection": {"path": str(run / "paired_collection.json")},
                "twin_gate": {"path": str(run / "twin_gate.json")},
                "controlled_manifest": controlled["controlled_manifest"],
                "zero_baseline_manifest": zero["zero_baseline_manifest"]}
    return sources, evidence


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--payload", type=Path, required=True)
    parser.add_argument("--output", type=Path, default=ROOT / "src/OID_analysis/runs/active-two-scene-v2/canonical")
    args = parser.parse_args()
    raw_root = args.payload / "src/OID_analysis/runs/formal-three"
    summary = []
    for scene in SCENES:
        full_mask, geometry = build_legacy_geometry(scene)
        reduced, metric, metric_meta = crop_stride_metric(full_mask, crop=CROP, stride=STRIDE)
        counts = (int(reduced.sum()), int((~reduced).sum()))
        if counts != EXPECTED[scene]:
            raise RuntimeError(f"unexpected exact Legacy mask counts for {scene}: {counts}")
        geometry_hash = hashlib.sha256(deterministic_json_bytes(geometry)).hexdigest()
        old_product = raw_root / scene / "r1/canonical/paired_product.npz"
        with __import__("numpy").load(old_product, allow_pickle=False) as old:
            old_mask = old["fluid_mask"]
            old_counts = (int(old_mask.sum()), int((~old_mask).sum()))
            if old_mask.shape != reduced.shape or __import__("numpy").array_equal(old_mask, reduced):
                raise RuntimeError(f"archived mask defect was not reproduced for {scene}")
        print(f"verified archived mask defect: {scene} old={old_counts} exact={counts}", file=sys.stderr)
        for realization in REALIZATIONS:
            source = raw_root / scene / realization
            destination = args.output / scene / realization
            sources, evidence = _canonical_and_evidence(source)
            metadata = build_canonical_paired_product(
                sources["controlled_fields"]["path"], sources["zero_baseline_fields"]["path"],
                sources["controlled_telemetry"]["path"], sources["zero_baseline_telemetry"]["path"], destination,
                realization_id=realization, fluid_mask=full_mask, cell_metric=metric,
                metric_metadata=metric_meta, crop=CROP, stride=STRIDE,
                source_artifacts=sources, geometry_declaration=geometry, evidence_artifacts=evidence,
            )
            loaded = load_canonical_product(destination)
            if loaded["metadata"] != metadata or metadata["geometry_declaration_sha256"] != geometry_hash:
                raise RuntimeError(f"loader/provenance verification failed: {scene}/{realization}")
            product = destination / metadata["product"]
            summary.append({"scene": scene, "realization": realization, "path": str(product),
                            "sha256": hashlib.sha256(product.read_bytes()).hexdigest(),
                            "size_bytes": product.stat().st_size, "fluid": counts[0], "solid": counts[1]})
    print(json.dumps(summary, indent=2))
    return 0

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