#!/usr/bin/env python3
"""
Standalone Zero-LIMS-Touch Executable Verifier for IIP-0060 / DEC-141 / GATE-39:
Cuff Humoral Multi-Stratum Coverage Reconciliation, Product-Bound Omission Guard,
Anti-PEG Upper-Tail Titre Characterization, and DAY28 Primed-Serum Disambiguation.

Zero wetlab_contract.py imports; zero mutations to frozen LIMS contracts,
ingest_wetlab_results.py, FASTAs, 36 Idea Graveyard rules, or live odds (+0.00 pp).
Deterministic under -B and -O -B.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import sys
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parent.parent
SIDE_CONTRACT_PATH = (
    ROOT / "data" / "protocols" / "iip0060_cuff_stratum_coverage_side_contract_v0.9.0.json"
)
DEFAULT_RECEIPT_PATH = (
    ROOT / "data" / "extracted" / "iip0060_cuff_stratum_coverage_verification_v0.9.0.json"
)


def clopper_pearson_u95_zero_failures(n: int, eta: float = 1.0) -> float:
    if n <= 0 or eta <= 0.0:
        return 1.0
    return min(1.0, (1.0 - (0.05 ** (1.0 / n))) / eta)


def evaluate_gate39_cuff_coverage(lot_manifest: dict[str, Any], side_contract: dict[str, Any]) -> dict[str, Any]:
    """Fail-closed evaluation of cross-stratum cuff humoral coverage on a Stage-0 lot manifest."""
    reasons: list[str] = []
    warnings: list[str] = []

    product_id = str(lot_manifest.get("product_id", ""))
    cuff_present = lot_manifest.get("cuff_present")
    cuff_arm = lot_manifest.get("cuff_bioconjugation_arm")
    rules = side_contract["cuff_arm_and_product_binding_rules"]

    # 1. Explicit non-cuff protection (never over-block non-cuff lots like un-cuffed Design Z or strict Design A)
    if cuff_present is False:
        return {
            "verdict": "NOT_APPLICABLE_NON_CUFF_LOT",
            "pass": True,
            "reasons": [],
            "warnings": [],
            "diagnostics": {"product_id": product_id, "cuff_present": False},
        }
    if cuff_present is not True:
        return {
            "verdict": "HOLD_UNDECLARED_CUFF_PRESENCE",
            "pass": False,
            "reasons": ["HOLD_UNDECLARED_CUFF_PRESENCE: lot manifest must explicitly declare boolean cuff_present."],
            "warnings": [],
            "diagnostics": {"product_id": product_id},
        }

    # 2. Enforce Wave-6 Design A strict zero-additional-biologics boundary (no Cuff v2.0 on Design A)
    if product_id in set(rules["design_a_product_ids"]) and cuff_arm == "CUFF_V2_ACELLULAR_SCR1_THBD_CD200":
        return {
            "verdict": "BLOCK_DESIGN_A_ZERO_ADDITIONAL_BIOLOGIC_BOUNDARY",
            "pass": False,
            "reasons": [
                "BLOCK_DESIGN_A_ZERO_ADDITIONAL_BIOLOGIC_BOUNDARY: Design A forbids Cuff v2.0 additional biologics (wave6_canonical_arm_manifest.json)."
            ],
            "warnings": [],
            "diagnostics": {"product_id": product_id, "cuff_bioconjugation_arm": cuff_arm},
        }

    lot_id = lot_manifest.get("lot_id")
    device_scope = lot_manifest.get("assembled_device_lot_scope")
    if not lot_id or not device_scope:
        reasons.append("HOLD_MISSING_LOT_OR_DEVICE_SCOPE: lot_id and assembled_device_lot_scope required for cross-stratum reconciliation.")

    batches = lot_manifest.get("stratum_batch_receipts")
    if not isinstance(batches, list) or len(batches) == 0:
        return {
            "verdict": "HOLD_CUFF_OMISSION_BYPASS_BLOCKED",
            "pass": False,
            "reasons": [
                "HOLD_CUFF_OMISSION_BYPASS_BLOCKED: cuff_present=True lot submitted zero cuff stratum batch receipts (omission bypass blocked regardless of opt-in boolean)."
            ],
            "warnings": [],
            "diagnostics": {"product_id": product_id, "cuff_present": True, "submitted_strata": []},
        }

    allowed_strata = set(side_contract["allowed_cuff_serum_challenge_strata"])
    sa_bearing = cuff_arm in set(rules["streptavidin_bearing_cuff_arms"])
    sa_free_arm = cuff_arm in set(rules["streptavidin_free_cuff_arms"])
    sa_free_verified = lot_manifest.get("streptavidin_free_cuff_verified") is True
    peg_free_verified = (
        cuff_arm == "ZWITTERIONIC_ALGINATE_PEG_FREE_CUFF"
        and lot_manifest.get("peg_free_cuff_verified") is True
    )

    if not sa_bearing and not sa_free_arm:
        reasons.append(f"HOLD_UNRECOGNIZED_CUFF_ARM: {cuff_arm!r} not in Gate 39 allowed cuff arms.")

    # Required strata by cuff chemistry
    required_baseline = ["NORMAL_DONOR_SERA"]
    if not peg_free_verified:
        required_baseline.append("HIGH_ANTI_PEG_IGG_GT_500NG_ML")
    if sa_bearing or not (sa_free_arm and sa_free_verified):
        required_baseline.append("ANTI_SA_POSITIVE_HUMAN_SERA")
    require_day28_primed = bool(sa_bearing or not (sa_free_arm and sa_free_verified))

    req_cfg = side_contract["stratum_requirements"]
    min_base_n = int(req_cfg["baseline_prevalence_strata_min_donors"])
    min_day28_n = int(req_cfg["day28_primed_sera_policy"]["min_independent_primed_donors"])
    upper_tail_cfg = req_cfg["high_anti_peg_upper_tail_policy"]

    by_stratum: dict[str, dict[str, Any]] = {}
    for idx, b in enumerate(batches):
        if not isinstance(b, dict):
            reasons.append(f"HOLD_MALFORMED_BATCH_RECEIPT: index {idx} not a dict.")
            continue
        # Reject any pooled multi-stratum batch
        if b.get("pooled_across_strata") is True or isinstance(b.get("cuff_serum_challenge_stratum"), list):
            reasons.append("FAIL_CUFF_ILLEGAL_STRATUM_POOLING: pooling across donor strata is prohibited (IIP-0020 / DEC-099).")
            continue
        st = b.get("cuff_serum_challenge_stratum")
        if st not in allowed_strata:
            reasons.append(f"FAIL_CUFF_ILLEGAL_STRATUM_POOLING: invalid stratum {st!r}.")
            continue
        if b.get("lot_id") != lot_id or b.get("assembled_device_lot_scope") != device_scope:
            reasons.append(
                f"HOLD_CUFF_CROSS_LOT_PROVENANCE_MISMATCH: stratum {st} lot/scope ({b.get('lot_id')}/{b.get('assembled_device_lot_scope')}) != ({lot_id}/{device_scope})."
            )
            continue
        by_stratum[st] = b

    # Check completeness
    missing: list[str] = [s for s in required_baseline if s not in by_stratum]
    if require_day28_primed and "DAY28_SA_FASL_PRIMED_SERA" not in by_stratum:
        missing.append("DAY28_SA_FASL_PRIMED_SERA")
    if missing:
        reasons.append(f"HOLD_CUFF_SERUM_STRATUM_COVERAGE_INCOMPLETE: missing required strata {missing}.")

    # Validate each submitted stratum receipt
    u95_by_stratum: dict[str, float] = {}
    for st, b in by_stratum.items():
        if b.get("single_stratum_status") != "CLEARED_CUFF_HUMORAL_HYDROLYSIS_AND_HEPATOCYTE_SAFETY_GATE":
            reasons.append(f"FAIL_CUFF_STRATUM_BATCH_NOT_CLEARED: {st} status={b.get('single_stratum_status')!r}.")
        n_donors = b.get("obs_cuff_serum_donor_count")
        n_fail = b.get("obs_cuff_serum_failing_donor_count")
        if not isinstance(n_donors, (int, float)) or not isinstance(n_fail, (int, float)):
            reasons.append(f"HOLD_CUFF_MISSING_DONOR_COUNTS: {st} missing donor or failing count.")
            continue
        n_int = int(round(float(n_donors)))
        fail_int = int(round(float(n_fail)))
        if fail_int > 0:
            reasons.append(f"FAIL_CUFF_STRATUM_DONOR_FAILURE: {st} recorded {fail_int} failing donors (max allowed = 0).")
        if st == "DAY28_SA_FASL_PRIMED_SERA":
            if n_int < min_day28_n:
                reasons.append(f"HOLD_CUFF_DAY28_PRIMED_UNDERPOWERED: {st} n={n_int} < {min_day28_n}.")
            elif n_int < min_base_n:
                warnings.append(
                    f"DAY28_PRIMED_SERA_POST_EXPOSURE_N_LT_12: n={n_int} (U95={clopper_pearson_u95_zero_failures(n_int):.4f}); n>=12 recommended where available."
                )
            if b.get("paired_pre_vs_day28_anti_sa_fold_documented") is not True:
                reasons.append("HOLD_CUFF_DAY28_PRIMED_FOLD_UNDOCUMENTED: paired pre vs Day-28 anti-SA IgG fold required.")
        else:
            if n_int < min_base_n:
                reasons.append(f"HOLD_CUFF_STRATUM_UNDERPOWERED_N_LT_12: {st} n={n_int} < {min_base_n} (U95={clopper_pearson_u95_zero_failures(n_int):.4f} > 0.2209).")
        if st == "HIGH_ANTI_PEG_IGG_GT_500NG_ML":
            n_hi = b.get("anti_peg_donors_ge_1000ng_ml")
            ceiling_waiver = b.get("anti_peg_cohort_ceiling_documented") is True
            if (not isinstance(n_hi, int) or n_hi < int(upper_tail_cfg["min_upper_tail_donors"])) and not ceiling_waiver:
                reasons.append(
                    f"HOLD_CUFF_ANTI_PEG_UPPER_TAIL_UNCHARACTERIZED: requires >= {upper_tail_cfg['min_upper_tail_donors']} donors >= 1000 ng/mL (or documented cohort-ceiling waiver)."
                )
        u95_by_stratum[st] = round(clopper_pearson_u95_zero_failures(n_int), 6)

    passed = len(reasons) == 0
    return {
        "verdict": "PASS_GATE39_CUFF_STRATUM_COVERAGE" if passed else reasons[0].split(":")[0],
        "pass": passed,
        "reasons": reasons,
        "warnings": warnings,
        "diagnostics": {
            "product_id": product_id,
            "cuff_bioconjugation_arm": cuff_arm,
            "required_baseline_strata": required_baseline,
            "require_day28_primed_sera": require_day28_primed,
            "submitted_strata": sorted(by_stratum.keys()),
            "missing_strata": missing,
            "u95_zero_failure_by_stratum": u95_by_stratum,
        },
    }


def run_self_tests(side_contract: dict[str, Any]) -> list[dict[str, Any]]:
    """Run 12 deterministic adversarial self-tests for GATE-39."""
    results: list[dict[str, Any]] = []

    def _rec(name: str, ok: bool, detail: str) -> None:
        results.append({"test": name, "passed": bool(ok), "detail": detail})

    # T01: Exact U95 and Yang 2016 prevalence math
    u12 = clopper_pearson_u95_zero_failures(12)
    u6 = clopper_pearson_u95_zero_failures(6)
    _rec(
        "T01_exact_u95_and_yang2016_expected_draw",
        math.isclose(u12, 0.22092222, abs_tol=1e-6)
        and math.isclose(u6, 0.39303776, abs_tol=1e-6)
        and math.isclose(12 * 0.07, 0.84, abs_tol=1e-9),
        f"U95(12)={u12:.6f}, U95(6)={u6:.6f}, E[hi_PEG]=0.84",
    )

    def _mk_batch(st: str, n: int = 12, fail: int = 0, lot: str = "LOT-001", scope: str = "DEV-SCOPE-001", **kw: Any) -> dict[str, Any]:
        rec: dict[str, Any] = {
            "cuff_serum_challenge_stratum": st,
            "lot_id": lot,
            "assembled_device_lot_scope": scope,
            "single_stratum_status": "CLEARED_CUFF_HUMORAL_HYDROLYSIS_AND_HEPATOCYTE_SAFETY_GATE",
            "obs_cuff_serum_donor_count": n,
            "obs_cuff_serum_failing_donor_count": fail,
        }
        if st == "HIGH_ANTI_PEG_IGG_GT_500NG_ML":
            rec.setdefault("anti_peg_donors_ge_1000ng_ml", 4)
        if st == "DAY28_SA_FASL_PRIMED_SERA":
            rec.setdefault("paired_pre_vs_day28_anti_sa_fold_documented", True)
        rec.update(kw)
        return rec

    full_sa_lot = {
        "product_id": "ISLET1_DESIGN_X_V090",
        "lot_id": "LOT-001",
        "assembled_device_lot_scope": "DEV-SCOPE-001",
        "cuff_present": True,
        "cuff_bioconjugation_arm": "SA_FASL_SA_THBD_PEG_MICROGEL_CUFF",
        "stratum_batch_receipts": [
            _mk_batch("NORMAL_DONOR_SERA", 12),
            _mk_batch("HIGH_ANTI_PEG_IGG_GT_500NG_ML", 12),
            _mk_batch("ANTI_SA_POSITIVE_HUMAN_SERA", 12),
            _mk_batch("DAY28_SA_FASL_PRIMED_SERA", 6),
        ],
    }

    # T02: Complete 4-stratum SA cuff lot passes (with Day-28 n=6 warning disclosed)
    r2 = evaluate_gate39_cuff_coverage(full_sa_lot, side_contract)
    _rec("T02_full_4stratum_sa_cuff_lot_passes", r2["pass"] and len(r2["warnings"]) == 1, r2["verdict"])

    # T03: NORMAL_DONOR_SERA alone fails closed naming 3 missing strata
    single_norm = dict(full_sa_lot, stratum_batch_receipts=[_mk_batch("NORMAL_DONOR_SERA", 12)])
    r3 = evaluate_gate39_cuff_coverage(single_norm, side_contract)
    _rec(
        "T03_single_normal_stratum_blocked",
        not r3["pass"] and r3["verdict"] == "HOLD_CUFF_SERUM_STRATUM_COVERAGE_INCOMPLETE" and len(r3["diagnostics"]["missing_strata"]) == 3,
        f"{r3['verdict']} missing={r3['diagnostics']['missing_strata']}",
    )

    # T04: Cuff-bearing lot with zero receipts omitted blocked
    omitted = dict(full_sa_lot, stratum_batch_receipts=[])
    r4 = evaluate_gate39_cuff_coverage(omitted, side_contract)
    _rec("T04_omission_bypass_blocked", not r4["pass"] and r4["verdict"] == "HOLD_CUFF_OMISSION_BYPASS_BLOCKED", r4["verdict"])

    # T05: Non-cuff lot (strict zero-biologic Design A) not over-blocked
    non_cuff = {"product_id": "ISLET1_DESIGN_A_V080_REF", "cuff_present": False}
    r5 = evaluate_gate39_cuff_coverage(non_cuff, side_contract)
    _rec("T05_non_cuff_design_a_not_overblocked", r5["pass"] and r5["verdict"] == "NOT_APPLICABLE_NON_CUFF_LOT", r5["verdict"])

    # T06: Design A attempting Cuff v2.0 blocked
    da_cuffv2 = {
        "product_id": "ISLET1_DESIGN_A_V080_REF",
        "cuff_present": True,
        "cuff_bioconjugation_arm": "CUFF_V2_ACELLULAR_SCR1_THBD_CD200",
        "stratum_batch_receipts": [_mk_batch("NORMAL_DONOR_SERA", 12)],
    }
    r6 = evaluate_gate39_cuff_coverage(da_cuffv2, side_contract)
    _rec("T06_design_a_cuff_v2_blocked", not r6["pass"] and r6["verdict"] == "BLOCK_DESIGN_A_ZERO_ADDITIONAL_BIOLOGIC_BOUNDARY", r6["verdict"])

    # T07: Lowering HIGH_ANTI_PEG_IGG_GT_500NG_ML to n=6 blocked
    underpowered = dict(
        full_sa_lot,
        stratum_batch_receipts=[
            _mk_batch("NORMAL_DONOR_SERA", 12),
            _mk_batch("HIGH_ANTI_PEG_IGG_GT_500NG_ML", 6),
            _mk_batch("ANTI_SA_POSITIVE_HUMAN_SERA", 12),
            _mk_batch("DAY28_SA_FASL_PRIMED_SERA", 6),
        ],
    )
    r7 = evaluate_gate39_cuff_coverage(underpowered, side_contract)
    _rec("T07_n6_baseline_stratum_underpowered_blocked", not r7["pass"] and r7["verdict"] == "HOLD_CUFF_STRATUM_UNDERPOWERED_N_LT_12", r7["verdict"])

    # T08: Clustered anti-PEG cohort (0 donors >= 1,000 ng/mL, no waiver) blocked
    clustered = dict(
        full_sa_lot,
        stratum_batch_receipts=[
            _mk_batch("NORMAL_DONOR_SERA", 12),
            _mk_batch("HIGH_ANTI_PEG_IGG_GT_500NG_ML", 12, anti_peg_donors_ge_1000ng_ml=0),
            _mk_batch("ANTI_SA_POSITIVE_HUMAN_SERA", 12),
            _mk_batch("DAY28_SA_FASL_PRIMED_SERA", 6),
        ],
    )
    r8 = evaluate_gate39_cuff_coverage(clustered, side_contract)
    _rec("T08_clustered_anti_peg_upper_tail_blocked", not r8["pass"] and r8["verdict"] == "HOLD_CUFF_ANTI_PEG_UPPER_TAIL_UNCHARACTERIZED", r8["verdict"])

    # T09: Cross-lot mismatch blocked
    cross_lot = dict(
        full_sa_lot,
        stratum_batch_receipts=[
            _mk_batch("NORMAL_DONOR_SERA", 12, lot="LOT-001"),
            _mk_batch("HIGH_ANTI_PEG_IGG_GT_500NG_ML", 12, lot="LOT-999"),
            _mk_batch("ANTI_SA_POSITIVE_HUMAN_SERA", 12, lot="LOT-001"),
            _mk_batch("DAY28_SA_FASL_PRIMED_SERA", 6, lot="LOT-001"),
        ],
    )
    r9 = evaluate_gate39_cuff_coverage(cross_lot, side_contract)
    _rec("T09_cross_lot_provenance_mismatch_blocked", not r9["pass"] and "CROSS_LOT" in r9["verdict"], r9["verdict"])

    # T10: Non-zero failing donor fails closed
    donor_fail = dict(
        full_sa_lot,
        stratum_batch_receipts=[
            _mk_batch("NORMAL_DONOR_SERA", 12),
            _mk_batch("HIGH_ANTI_PEG_IGG_GT_500NG_ML", 12, fail=1),
            _mk_batch("ANTI_SA_POSITIVE_HUMAN_SERA", 12),
            _mk_batch("DAY28_SA_FASL_PRIMED_SERA", 6),
        ],
    )
    r10 = evaluate_gate39_cuff_coverage(donor_fail, side_contract)
    _rec("T10_donor_failure_rejected", not r10["pass"] and r10["verdict"] == "FAIL_CUFF_STRATUM_DONOR_FAILURE", r10["verdict"])

    # T11: Pooled multi-stratum batch rejected
    pooled = dict(
        full_sa_lot,
        stratum_batch_receipts=[
            _mk_batch("NORMAL_DONOR_SERA", 12, pooled_across_strata=True),
        ],
    )
    r11 = evaluate_gate39_cuff_coverage(pooled, side_contract)
    _rec("T11_illegal_stratum_pooling_rejected", not r11["pass"] and r11["verdict"] == "FAIL_CUFF_ILLEGAL_STRATUM_POOLING", r11["verdict"])

    # T12: Verified streptavidin-free Cuff v2.0 on Arm B passes with NORMAL + HIGH_ANTI_PEG (n>=12 each)
    sa_free_lot = {
        "product_id": "ISLET1_DESIGN_B_V090",
        "lot_id": "LOT-B02",
        "assembled_device_lot_scope": "DEV-SCOPE-B02",
        "cuff_present": True,
        "cuff_bioconjugation_arm": "CUFF_V2_ACELLULAR_SCR1_THBD_CD200",
        "streptavidin_free_cuff_verified": True,
        "stratum_batch_receipts": [
            _mk_batch("NORMAL_DONOR_SERA", 12, lot="LOT-B02", scope="DEV-SCOPE-B02"),
            _mk_batch("HIGH_ANTI_PEG_IGG_GT_500NG_ML", 12, lot="LOT-B02", scope="DEV-SCOPE-B02"),
        ],
    }
    r12 = evaluate_gate39_cuff_coverage(sa_free_lot, side_contract)
    _rec("T12_streptavidin_free_cuff_v2_scoped_cleanly", r12["pass"] and not r12["diagnostics"]["require_day28_primed_sera"], r12["verdict"])

    return results


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


def main() -> int:
    parser = argparse.ArgumentParser(description="Verify GATE-39 (IIP-0060 / DEC-141) cuff humoral stratum coverage gate.")
    parser.add_argument("--write-receipt", type=Path, default=None, help="Write deterministic verification receipt JSON.")
    args = parser.parse_args()

    side_contract = json.loads(SIDE_CONTRACT_PATH.read_text(encoding="utf-8"))
    self_tests = run_self_tests(side_contract)
    passed = sum(1 for t in self_tests if t["passed"])
    all_ok = passed == len(self_tests)

    receipt = {
        "schema_version": "iip0060_cuff_stratum_coverage_verification_v0.9.0",
        "gate_id": "GATE-39",
        "contribution_id": "IIP-0060",
        "decision_id": "DEC-141",
        "generated_date": "2026-12-03",
        "overall_status": "PASSED" if all_ok else "FAILED",
        "live_odds_delta_pp": 0.0,
        "side_contract_sha256": sha256_file(SIDE_CONTRACT_PATH),
        "self_tests_passed": passed,
        "self_tests_total": len(self_tests),
        "self_tests": self_tests,
    }

    if args.write_receipt is not None:
        args.write_receipt.parent.mkdir(parents=True, exist_ok=True)
        args.write_receipt.write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8")

    print(
        f"{'PASS' if all_ok else 'FAIL'}: GATE-39 (IIP-0060 / DEC-141) self_tests={passed}/{len(self_tests)} "
        f"odds_delta=+0.00pp side_contract_sha256={receipt['side_contract_sha256'][:16]}..."
    )
    return 0 if all_ok else 1


if __name__ == "__main__":
    sys.exit(main())
