#!/usr/bin/env python3
from __future__ import annotations

import hashlib
import json
import math
import zipfile
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "research" / "fine_structure" / "FROZEN_CHECKPOINT_2026-08-14.json"
BUNDLE = ROOT / "research" / "fine_structure" / "UTFANSWF_1_137_RESON8_INDEPENDENT_VERIFICATION_2026-08-14_TIGHT_LICENSE.zip"
OUT = ROOT / "results" / "row27_fine_structure" / "result.json"
EMBEDDING_RESULT = ROOT / "results" / "utfanswf_embedding" / "result.json"
OUT.parent.mkdir(parents=True, exist_ok=True)

EXPECTED_BUNDLE_SHA256 = "9ce68f81e05a438398c901488a09c8815453c5ba02395ed8fb85bb3709b3ae50"


def sha256_bytes(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def sha256_file(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(1024 * 1024), b""):
            h.update(chunk)
    return h.hexdigest()


def verify_internal_manifest(bundle: Path) -> tuple[bool, dict[str, object]]:
    with zipfile.ZipFile(bundle, "r") as zf:
        names = set(zf.namelist())
        manifest_name = next((n for n in names if n.endswith("SHA256SUMS.txt")), None)
        if manifest_name is None:
            return False, {"manifest_present": False, "checked": 0, "failed": ["SHA256SUMS.txt missing"]}
        manifest = zf.read(manifest_name).decode("utf-8")
        failures: list[str] = []
        checked = 0
        for raw in manifest.splitlines():
            line = raw.strip()
            if not line:
                continue
            parts = line.split(None, 1)
            if len(parts) != 2:
                failures.append(f"malformed manifest line: {line}")
                continue
            expected, filename = parts
            filename = filename.lstrip("*").strip()
            # Bundle is flat in the frozen verification edition. If a prefix appears,
            # match by exact entry first and then by basename.
            target = filename if filename in names else next((n for n in names if Path(n).name == Path(filename).name), None)
            if target is None:
                failures.append(f"missing: {filename}")
                continue
            checked += 1
            actual = sha256_bytes(zf.read(target))
            if actual.lower() != expected.lower():
                failures.append(f"hash mismatch: {filename}")
        return not failures, {
            "manifest_present": True,
            "checked": checked,
            "failed": failures,
        }



def audit_late_handoff_calibration(bundle: Path) -> dict[str, object]:
    """Mechanically determine whether preserved late runners are endpoint-calibrated.

    This is a provenance/claim-boundary check, not a criticism of the diagnostics.
    A source-complete final handoff must be reconstructed without deriving its local
    response coefficient/slope from the preserved A_PRE/A_POST checkpoints.
    """
    with zipfile.ZipFile(bundle, "r") as zf:
        names = set(zf.namelist())
        required = [
            "hardened_incremental_runner_v4.py",
            "verify_portable_v4.py",
            "reduced_coupled_runner_v3.py",
            "GRIFFIN_LATE_RECOVERY_CHECKPOINT_2026-08-13.md",
        ]
        missing = [n for n in required if n not in names]
        if missing:
            return {"pass": False, "missing": missing}
        v4 = zf.read("hardened_incremental_runner_v4.py").decode("utf-8", "ignore")
        portable = zf.read("verify_portable_v4.py").decode("utf-8", "ignore")
        v3 = zf.read("reduced_coupled_runner_v3.py").decode("utf-8", "ignore")
        checkpoint = zf.read("GRIFFIN_LATE_RECOVERY_CHECKPOINT_2026-08-13.md").decode("utf-8", "ignore")

    v4_endpoint_handoff = all(x in v4 for x in ["A_PRE=137.03735243", "A_POST=137.00222764", "LAMBDA_SW=(R_POST-R_PRE-drpost)/swpost"])
    portable_endpoint_handoff = all(x in portable for x in ["A_PRE=137.03735243", "A_POST=137.00222764", "LAMBDA_SW=(R_POST-R_PRE-drpost)/swpost"])
    v3_endpoint_slope = all(x in v3 for x in ["A_PRE=137.03735243", "A_POST=137.00222764", "M_SLOPE=-qmix0/(A_POST-A_PRE)"])
    checkpoint_boundary = (
        "exact late coupled runner/Jacobian must be restored or rebuilt" in checkpoint
        and "Do NOT promote" in checkpoint
        and "independently derive the exact hardened weak-angle handoff" in checkpoint
    )
    endpoint_calibration_present = bool(v4_endpoint_handoff and portable_endpoint_handoff and v3_endpoint_slope)
    return {
        "pass": bool(endpoint_calibration_present and checkpoint_boundary),
        "endpoint_calibration_present": endpoint_calibration_present,
        "v4_handoff_uses_PRE_POST": v4_endpoint_handoff,
        "portable_v4_handoff_uses_PRE_POST": portable_endpoint_handoff,
        "reduced_v3_slope_uses_PRE_POST": v3_endpoint_slope,
        "checkpoint_explicitly_forbids_final_promotion": checkpoint_boundary,
        "interpretation": "Preserved late runners are valid reduced/incremental diagnostics but are not an independently reconstructed source-complete handoff.",
    }


def upstream_uv_boundary_audit() -> dict[str, object]:
    if not EMBEDDING_RESULT.exists():
        return {"pass": False, "status": "MISSING_UTFANSWF_EMBEDDING_RESULT"}
    emb = json.loads(EMBEDDING_RESULT.read_text(encoding="utf-8"))
    audit = emb.get("metrics", {}).get("blind_UV_boundary_audit", {})
    return {
        "pass": bool(
            audit.get("status") == "BLOCKED_BY_HEAVY_THRESHOLD_BOUNDARY"
            and audit.get("active_blind_prediction_available") is False
            and audit.get("pinned_corrected_threshold_closure_allowed_as_blind_input") is False
        ),
        "status": audit.get("status"),
        "active_blind_prediction_available": audit.get("active_blind_prediction_available"),
        "missing_independent_heavy_boundaries": audit.get("missing_independent_heavy_boundaries", []),
        "role": "separate UV/GUT electromagnetic route; does not invalidate the low-energy distributed blind checkpoint",
    }

data = json.loads(DATA.read_text(encoding="utf-8"))
chron = data["chronology"]
cmp = data["post_unblinding_comparison"]
contract = data["blind_contract"]

blind_checkpoint = float(chron["late_pre_mixed_blind_checkpoint_inverse_alpha"])
post_mixed = float(chron["post_two_verified_mixed_corrections_inverse_alpha"])
holdout = float(cmp["withheld_inverse_alpha"])

calc_diff = blind_checkpoint - holdout
calc_pct = abs(calc_diff) / holdout * 100.0
calc_agreement = 100.0 - calc_pct

bundle_sha = sha256_file(BUNDLE)
internal_ok, internal_detail = verify_internal_manifest(BUNDLE)
late_handoff_audit = audit_late_handoff_calibration(BUNDLE)
uv_boundary_audit = upstream_uv_boundary_audit()

blind_contract_pass = (
    contract["measured_electromagnetic_alpha_used_as_solve_input"] is False
    and contract["fit_to_inverse_137_target"] is False
    and contract["hidden_GRIFFIN_example_normalization"] is False
    and contract["double_counting_allowed"] is False
    and contract["physical_holdout_used_only_after_freeze"] is True
    and data["solve_inputs_include_holdout"] is False
)

checks = {
    "blind_contract_declared_and_holdout_excluded_from_solve": blind_contract_pass,
    "frozen_checkpoint_matches_record": math.isclose(blind_checkpoint, 137.03735243, rel_tol=0.0, abs_tol=5e-12),
    "post_mixed_checkpoint_matches_record": math.isclose(post_mixed, 137.00222764, rel_tol=0.0, abs_tol=5e-12),
    "post_unblinding_difference_recomputes": math.isclose(calc_diff, float(cmp["checkpoint_minus_holdout"]), rel_tol=0.0, abs_tol=5e-10),
    "post_unblinding_percent_recomputes": math.isclose(calc_pct, float(cmp["absolute_percent_error"]), rel_tol=0.0, abs_tol=5e-13),
    "historical_bracket_holds": post_mixed < holdout < blind_checkpoint,
    "verification_bundle_sha256_matches": bundle_sha == EXPECTED_BUNDLE_SHA256 == data["verification_bundle"]["sha256"],
    "verification_bundle_internal_manifest_passes": internal_ok,
    "final_source_complete_claim_remains_false": data["final_source_complete_claim"] is False,
    "independent_verification_not_overclaimed": data["verification_bundle"]["independent_verification_status"] == "REQUESTED_PENDING",
    "late_GRIFFIN_endpoint_calibration_detected_and_not_promoted": bool(late_handoff_audit["pass"]),
    "separate_UV_GUT_route_blocked_without_importing_pinned_EW_threshold_solution": bool(uv_boundary_audit["pass"]),
}

all_pass = all(checks.values())
verdict = "PASS" if all_pass else "FAIL"
status = (
    "PASS_BLIND_FINE_STRUCTURE_CHECKPOINT__FINAL_SOURCE_COMPLETE_GATE_OPEN"
    if all_pass
    else "FAIL_FINE_STRUCTURE_REPRODUCIBILITY_OR_BLINDNESS_GATE"
)

result = {
    "row": 27,
    "gate": "fine_structure_blind_checkpoint",
    "context": "POST_RELEASE_RESEARCH",
    "tier": "Diagnostic",
    "verdict": verdict,
    "blocking": False,
    "status": status,
    "checks": checks,
    "blind_checkpoint": {
        "alpha_inverse_0": blind_checkpoint,
        "role": "closest legitimate blind intermediate checkpoint",
        "final_source_complete_prediction": False,
    },
    "post_mixed_verified_rung": {
        "alpha_inverse_0": post_mixed,
        "role": "after two verified coupled mixed O(alpha^2 alpha_s) corrections",
    },
    "post_unblinding_comparison": {
        "withheld_alpha_inverse_0": holdout,
        "checkpoint_minus_holdout": calc_diff,
        "absolute_percent_error": calc_pct,
        "numerical_agreement_percent": calc_agreement,
        "historical_bracket": f"{post_mixed} < {holdout} < {blind_checkpoint}",
    },
    "blind_contract": contract,
    "verification": {
        "bundle": str(BUNDLE.relative_to(ROOT)),
        "bundle_sha256": bundle_sha,
        "internal_sha256_manifest": internal_detail,
        "independent_status": data["verification_bundle"]["independent_verification_status"],
    },
    "source_complete_handoff_audit": late_handoff_audit,
    "separate_UV_GUT_route_audit": uv_boundary_audit,
    "open_gates": {
        "low_energy_distributed_GRIFFIN_route": data["open_gate"],
        "UV_GUT_route": "derive independent corrected heavy-threshold boundary data before a blind electromagnetic downward solve",
    },
    "notes": (
        "Blind 1/137 intermediate checkpoint and verification provenance are preserved and reproducible; "
        "the final source-complete electroweak handoff remains open. The preserved late GRIFFIN runners are mechanically identified as endpoint-calibrated diagnostics, and the separate UV/GUT route is blocked by missing independent heavy-threshold boundary data; no final 1/137 derivation claim is made."
    ),
}

OUT.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
print(json.dumps(result, indent=2))
