#!/usr/bin/env python3
"""
Standalone Zero-LIMS-Touch Verifier & Executable Stage-0 Switch Evaluator for
IIP-0051 / DEC-131 / GATE-33 (`Gate 33-HTMPK-AZT-PK`) / GY-002 Amendment:
  "Bind Designs Y and D hTMPK-F105Y/AZT gates (Y-09 / D1-04) to clinical AZT
   exposure, intracellular AZT-MP/TP PK, >= 10^6-cell clonogenic dynamic range,
   Marin 2012 counter-evidence, and post-mitotic scope boundaries"
  (Community submission by Hayley / @hsmosshs; GitHub Issue #51)

Capabilities:
  1. Verifies strict Zero-LIMS-Touch & Frozen SHA-256 invariance across
     wetlab_contract.py, ingest_wetlab_results.py, wetlab_endpoint_contract_v0.8.0.json,
     iip0044_foundry_v1_3_biologics_side_contract_v0.8.0.json,
     islet1_combinatorial_pareto_and_ladder_v0.8.0.json, and Playbook sec 4.1.20.
  2. Re-derives exact clinical human AZT exposure anchors (Wang et al. 1999
     PMID:10390227: 1.5 ug/mL = 5.6129 uM alone, 1.2 ug/mL = 4.4903 uM with
     abacavir at MW 267.24 g/mol; 100-200 uM static in vitro = 17.82x-44.54x Cmax),
     rat mitochondrial TK2 IC50 context (7.0 uM, McKee et al. 2004 PMID:15371631),
     and clonogenic dynamic-range bounds (proving why 70% flow-cytometry death =
     0.5229 log10 is incommensurable with >= 4.0-log10 clonogenic clearance and
     why >= 10^6 plated clonogenic cells/arm are required).
  3. Provides fail-closed, strict-JSON executable Stage-0 Gate 33 adjudication
     (`evaluate_gate33_htmpk_azt_switch`, `--evaluate-azt-switch <json>`) with:
       - Separate promoter qualification (`CDK1p` Y-09 vs 404-bp `CDK1_300` D1-04)
       - Hard GY-002 rejection (`FAIL_GY002_POSTMITOTIC_SCOPE_VIOLATION`, exit 3)
         if claimed as a post-mitotic whole-graft erasability substitute
       - Rejection of supraphysiologic >= 50 uM-only AZT certification
       - Mandatory intracellular AZT-MP/TP LC-MS + >= 10^6 clonogenic arm +
         matched 10 nM AP1903 iCasp9 comparator + 1:100 mature Stage-7 beta-cell
         bystander viability/GSIS & mitochondrial safety check
       - Hard firewall preserving primary AAVS1 iCasp9 (`primary_aavs1_icasp9_gate_unaffected = True`)
  4. Audits Playbook Y-09/D1-04/R3P-05 unpinned AZT gap, GY-002 sync,
     ISLET-1-BLUEPRINT.md Design Y/D namespace disambiguation, and
     stage0_decision_tree_v1.json append-only block parity.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import sys
from pathlib import Path
from typing import Any, Dict, List, Mapping, Optional, Tuple

sys.dont_write_bytecode = True

SCRIPT_PATH = Path(__file__).resolve()
SCRIPT_DIR = SCRIPT_PATH.parent
REPO_ROOT = SCRIPT_DIR.parent

GENERATED_DATE = "2026-12-01"
CONTRIBUTION_ID = "IIP-0051"
DECISION_ID = "DEC-131"
GATE_ID = "GATE-33"
GATE_ALIAS = "Gate 33-HTMPK-AZT-PK"

SIDE_CONTRACT_REL = "data/protocols/iip0051_htmpk_azt_switch_gate33_side_contract_v0.8.0.json"
VERIFICATION_REL = "data/extracted/iip0051_htmpk_azt_switch_verification_v0.8.0.json"
PROTOCOL_DOC_REL = "docs/GATE-33-HTMPK-AZT-CLINICAL-PK-AND-CLONOGENIC-PROTOCOL.md"
DECISION_TREE_REL = "data/protocols/stage0_decision_tree_v1.json"
DECISION_TREE_KEY = "htmpk_f105y_azt_clinical_pk_and_clonogenic_gate33_iip_0051"
GRAVEYARD_REL = "data/graveyard/idea_graveyard_v0.5.json"
PLAYBOOK_REL = "docs/STAGE-0-EXECUTION-PLAYBOOK.md"
BLUEPRINT_REL = "ISLET-1-BLUEPRINT.md"
GATE0V_REL = "docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md"

FROZEN_SHA256_PINS: Dict[str, str] = {
    "scripts/wetlab_contract.py": "331ecd2f2d8602dfceae8b89263d0f360cfadfd0638a46d7d668a376294cfc73",
    "scripts/ingest_wetlab_results.py": "e050593675170515382257ce379449db596c87cc06ffc26d31d128e127630cb1",
    "data/protocols/wetlab_endpoint_contract_v0.8.0.json": "757bc1d9c2722c129cc4fd5962e8995b9f5bc5f7035f8530f5716da9aa2ac26f",
    "data/protocols/iip0044_foundry_v1_3_biologics_side_contract_v0.8.0.json": "458a67aee973579d1091e50e97c31bbb356072ff9f4b21ab6184bc403d19f51e",
    "data/extracted/islet1_combinatorial_pareto_and_ladder_v0.8.0.json": "460ebc1939eb98b38627eaa7d6603c086e5a75c127fc1ddeced0d5a325305f40",
}
EXPECTED_PLAYBOOK_SEC4120_SHA256 = "e3fb5ec701678dfdeb62a77c15866327842b60b6b4c503cb86dfc79885a626a8"

ALLOWED_PROMOTER_CONSTRUCTS = frozenset({
    "DESIGN_Y_CLYBL_CDK1P_HTMPK_F105Y",
    "DESIGN_D_CLYBL_404BP_CDK1_300_HTMPK_F105Y",
})
AZT_MW_G_MOL = 267.24
HUMAN_CMAX_ALONE_UG_ML = 1.5
HUMAN_CMAX_WITH_ABC_UG_ML = 1.2
MAX_CERTIFYING_CLINICAL_AZT_PEAK_UM = 10.0
MIN_CLINICAL_AZT_DAYS = 5.0
MIN_CLONOGENIC_PLATED = 1_000_000
MIN_CLONOGENIC_L95_LOG10 = 4.0
MIN_BYSTANDER_BETA_VIAB_L95_PCT = 85.0
MIN_BYSTANDER_BETA_GSIS_L95_PCT = 85.0


class StrictJsonError(ValueError):
    """Raised on malformed, duplicate-key, or non-finite JSON input."""


def _reject_nonfinite_constant(tok: str) -> Any:
    raise StrictJsonError(f"Non-finite JSON constant rejected: {tok}")


def _reject_duplicate_keys_pairs_hook(pairs: List[Tuple[str, Any]]) -> Dict[str, Any]:
    out: Dict[str, Any] = {}
    for k, v in pairs:
        if k in out:
            raise StrictJsonError(f"Duplicate JSON object key rejected: {k!r}")
        out[k] = v
    return out


def load_strict_json_text(text: str, label: str = "input") -> Any:
    try:
        return json.loads(
            text,
            parse_constant=_reject_nonfinite_constant,
            object_pairs_hook=_reject_duplicate_keys_pairs_hook,
        )
    except StrictJsonError:
        raise
    except Exception as exc:
        raise StrictJsonError(f"Invalid JSON in {label}: {exc}") from exc


def load_strict_json_file(path: Path) -> Any:
    return load_strict_json_text(path.read_text(encoding="utf-8"), label=str(path))


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


def _extract_playbook_sec4120_sha256(playbook_path: Path) -> str:
    pb_norm = playbook_path.read_text(encoding="utf-8").replace("\r\n", "\n")
    start_marker = "#### 4.1.20 Preregistered Autologous `D1b-Auto-C v2`"
    end_marker = "<!-- END_IIP0035_PLAYBOOK_SECTION_4_1_20 -->"
    start_idx = pb_norm.find(start_marker)
    end_idx = pb_norm.find(end_marker, start_idx if start_idx >= 0 else 0)
    if start_idx == -1 or end_idx == -1:
        raise RuntimeError("Could not locate Playbook section 4.1.20 canonical boundaries")
    body = pb_norm[start_idx:end_idx].strip()
    return hashlib.sha256(body.encode("utf-8")).hexdigest()


def _is_real_number(val: Any) -> bool:
    return isinstance(val, (int, float)) and not isinstance(val, bool) and math.isfinite(float(val))


def _is_strict_int(val: Any) -> bool:
    return isinstance(val, int) and not isinstance(val, bool)


def compute_azt_pk_and_clonogenic_anchors() -> Dict[str, Any]:
    """Re-derive exact human AZT Cmax micromolar conversions and clonogenic bounds."""
    cmax_alone_uM = (HUMAN_CMAX_ALONE_UG_ML / AZT_MW_G_MOL) * 1000.0
    cmax_abc_uM = (HUMAN_CMAX_WITH_ABC_UG_ML / AZT_MW_G_MOL) * 1000.0
    fold_100_lo = 100.0 / cmax_alone_uM
    fold_100_hi = 100.0 / cmax_abc_uM
    fold_200_lo = 200.0 / cmax_alone_uM
    fold_200_hi = 200.0 / cmax_abc_uM
    marin_70pct_log10 = -math.log10(1.0 - 0.70)
    # Exact 1-sided 95% binomial zero-survivor sample size for U95 <= 1e-4 (4-log10 kill):
    n_zero_surv_4log = math.ceil(math.log(0.05) / math.log(1.0 - 1e-4))
    return {
        "azt_mw_g_mol": AZT_MW_G_MOL,
        "human_300mg_cmax_alone_uM": round(cmax_alone_uM, 4),
        "human_300mg_cmax_with_abacavir_uM": round(cmax_abc_uM, 4),
        "static_100uM_vs_cmax_fold_range": [round(fold_100_lo, 2), round(fold_100_hi, 2)],
        "static_200uM_vs_cmax_fold_range": [round(fold_200_lo, 2), round(fold_200_hi, 2)],
        "rat_mitochondrial_tk2_ic50_uM": 7.0,
        "marin_2012_70pct_flow_death_nominal_log10": round(marin_70pct_log10, 4),
        "exact_zero_survivor_clonogenic_trials_for_u95_le_1e_4": n_zero_surv_4log,
        "min_required_clonogenic_cells_plated_per_arm": MIN_CLONOGENIC_PLATED,
    }


def evaluate_gate33_htmpk_azt_switch(observation: Mapping[str, Any]) -> Dict[str, Any]:
    """
    Fail-closed executable Stage-0 evaluator for Gate 33 (`Gate 33-HTMPK-AZT-PK`).

    HARD INVARIANTS:
      - `postmitotic_whole_graft_substitute_authorized` is ALWAYS False.
      - `primary_aavs1_icasp9_gate_unaffected` is ALWAYS True on chr13 backup HOLDs.
      - Claiming post-mitotic whole-graft substitution emits FAIL_GY002_POSTMITOTIC_SCOPE_VIOLATION (exit 3).
    """
    reasons: List[str] = []

    def _res(
        verdict: str,
        exit_code: int,
        chr13_qualified: bool,
        derived: Dict[str, Any],
    ) -> Dict[str, Any]:
        return {
            "gate_id": GATE_ID,
            "gate_alias": GATE_ALIAS,
            "verdict": verdict,
            "exit_code": exit_code,
            "chr13_backup_switch_qualified": bool(chr13_qualified),
            "postmitotic_whole_graft_substitute_authorized": False,
            "primary_aavs1_icasp9_gate_unaffected": True,
            "reasons": reasons,
            "derived_summary": derived,
        }

    if not isinstance(observation, Mapping):
        reasons.append("Observation payload must be a JSON object.")
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, {})

    # 1. Hard GY-002 post-mitotic scope boundary check
    claimed_pm = observation.get("claimed_as_postmitotic_whole_graft_substitute")
    if not isinstance(claimed_pm, bool):
        reasons.append("Missing boolean claimed_as_postmitotic_whole_graft_substitute declaration.")
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, {})
    if claimed_pm is True:
        reasons.append(
            "GY-002 HARD BLOCK: CDK1p/CDK1_300::hTMPK-F105Y is dividing-escape containment only "
            "and is NEVER a post-mitotic whole-graft erasability substitute for pan-lineage AAVS1 iCasp9/AP1903."
        )
        return _res("FAIL_GY002_POSTMITOTIC_SCOPE_VIOLATION", 3, False, {"claimed_postmitotic_substitute": True})

    # 2. Separate promoter architecture check (Y-09 CDK1p vs D1-04 404-bp CDK1_300)
    construct_id = observation.get("promoter_construct_id")
    if construct_id not in ALLOWED_PROMOTER_CONSTRUCTS:
        reasons.append(
            f"promoter_construct_id={construct_id!r} must be explicitly declared in {sorted(ALLOWED_PROMOTER_CONSTRUCTS)} "
            "(Y-09 CDK1p and D1-04 404-bp CDK1_300 must be qualified separately)."
        )
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, {})

    # 3. Validate clinical AZT PK & intracellular AZT-MP/TP block
    pk_arm = observation.get("clinical_azt_pk_arm")
    if not isinstance(pk_arm, Mapping):
        reasons.append("Missing clinical_azt_pk_arm object.")
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, {})

    peak_uM = pk_arm.get("certifying_azt_peak_uM")
    days = pk_arm.get("exposure_duration_days")
    lcms_ok = pk_arm.get("intracellular_azt_mp_tp_lcms_verified")
    if not _is_real_number(peak_uM) or float(peak_uM) <= 0.0:
        reasons.append(f"Invalid certifying_azt_peak_uM={peak_uM!r}.")
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, {})
    if not _is_real_number(days) or float(days) <= 0.0:
        reasons.append(f"Invalid exposure_duration_days={days!r}.")
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, {})
    if not isinstance(lcms_ok, bool):
        reasons.append("Missing boolean intracellular_azt_mp_tp_lcms_verified.")
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, {})

    derived: Dict[str, Any] = {
        "promoter_construct_id": construct_id,
        "certifying_azt_peak_uM": float(peak_uM),
        "exposure_duration_days": float(days),
        "intracellular_azt_mp_tp_lcms_verified": lcms_ok,
    }

    if float(peak_uM) > MAX_CERTIFYING_CLINICAL_AZT_PEAK_UM:
        reasons.append(
            f"Certifying AZT peak {float(peak_uM):.2f} uM exceeds clinical rescue ceiling "
            f"<= {MAX_CERTIFYING_CLINICAL_AZT_PEAK_UM:.1f} uM (human 300 mg oral Cmax ~4.49-5.61 uM; "
            "static 50-200 uM AZT may serve only as a non-certifying mechanistic positive control)."
        )
        return _res("HOLD_SUPRAPHYSIOLOGIC_AZT_ONLY_NOT_CLINICAL_PK", 2, False, derived)

    if float(days) < MIN_CLINICAL_AZT_DAYS or not lcms_ok:
        reasons.append(
            f"Clinical AZT rescue arm requires >= {MIN_CLINICAL_AZT_DAYS:.0f}-day exposure "
            "(avoiding false-failing 1-2 h single-pulse shortcuts) AND verified intracellular AZT-MP/AZT-TP LC-MS."
        )
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, derived)

    # 4. Validate clonogenic assay dynamic range & matched 10 nM AP1903 iCasp9 comparator
    clono = observation.get("clonogenic_kill_assay")
    if not isinstance(clono, Mapping):
        reasons.append("Missing clonogenic_kill_assay object.")
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, derived)

    assay_type = clono.get("assay_modality")
    n_plated = clono.get("n_clonogenic_cells_plated_per_arm")
    l95_log10 = clono.get("l95_log10_dividing_kill")
    zero_rebound = clono.get("zero_post_washout_colony_rebound")
    ap1903_comp = clono.get("matched_10nM_ap1903_icasp9_comparator_included")

    if assay_type != "CLONOGENIC_LIMITING_DILUTION_OUTGROWTH":
        reasons.append(
            f"assay_modality={assay_type!r} rejected: flow-cytometry-only readouts cannot resolve >= 4.0-log10 kill; "
            "CLONOGENIC_LIMITING_DILUTION_OUTGROWTH is required."
        )
        return _res("HOLD_INSUFFICIENT_CLONOGENIC_DYNAMIC_RANGE", 2, False, derived)

    if not _is_strict_int(n_plated) or n_plated < MIN_CLONOGENIC_PLATED:
        reasons.append(
            f"n_clonogenic_cells_plated_per_arm={n_plated!r} < {MIN_CLONOGENIC_PLATED:,} required for >= 4.0-log10 dynamic range."
        )
        return _res("HOLD_INSUFFICIENT_CLONOGENIC_DYNAMIC_RANGE", 2, False, derived)

    if not _is_real_number(l95_log10) or not isinstance(zero_rebound, bool) or not isinstance(ap1903_comp, bool):
        reasons.append("Missing or invalid l95_log10_dividing_kill, zero_post_washout_colony_rebound, or matched_10nM_ap1903_icasp9_comparator_included.")
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, derived)

    if not ap1903_comp:
        reasons.append("Matched 10 nM AP1903 iCasp9 comparator arm (GY-026 non-inferiority precedent) is mandatory.")
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, derived)

    # 5. Validate 1:100 spike-in mature Stage-7 beta-cell bystander & mitochondrial safety
    byst = observation.get("mature_beta_bystander_and_mito_safety")
    if not isinstance(byst, Mapping):
        reasons.append("Missing mature_beta_bystander_and_mito_safety object.")
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, derived)

    viab_l95 = byst.get("mature_beta_viability_l95_pct")
    gsis_l95 = byst.get("mature_beta_gsis_retention_l95_pct")
    mito_ok = byst.get("mitochondrial_dttp_safety_check_passed")
    if not _is_real_number(viab_l95) or not _is_real_number(gsis_l95) or not isinstance(mito_ok, bool):
        reasons.append("Invalid mature_beta_bystander_and_mito_safety fields.")
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, derived)

    derived.update({
        "n_clonogenic_cells_plated_per_arm": n_plated,
        "l95_log10_dividing_kill": float(l95_log10),
        "zero_post_washout_colony_rebound": zero_rebound,
        "mature_beta_viability_l95_pct": float(viab_l95),
        "mature_beta_gsis_retention_l95_pct": float(gsis_l95),
        "mitochondrial_dttp_safety_check_passed": mito_ok,
    })

    if float(viab_l95) < MIN_BYSTANDER_BETA_VIAB_L95_PCT or float(gsis_l95) < MIN_BYSTANDER_BETA_GSIS_L95_PCT or not mito_ok:
        reasons.append(
            f"Mature Stage-7 beta-cell sparing / mitochondrial safety failed "
            f"(viab L95={float(viab_l95):.1f}% [>=85%], GSIS L95={float(gsis_l95):.1f}% [>=85%], mito_ok={mito_ok}; "
            "Sato 2013 bystander / McKee 2004 mitochondrial IC50 ~7 uM risk)."
        )
        return _res("HOLD_BYSTANDER_OR_MITOCHONDRIAL_BETA_TOXICITY", 2, False, derived)

    if float(l95_log10) < MIN_CLONOGENIC_L95_LOG10 or not zero_rebound:
        reasons.append(
            f"Clinical-exposure AZT dividing-cell clonogenic kill L95={float(l95_log10):.2f} log10 (< 4.0) "
            f"or post-washout colony rebound observed (zero_rebound={zero_rebound}). "
            "Holding chr13 hTMPK-F105Y switch credit while leaving primary AAVS1 iCasp9 gate unaffected."
        )
        return _res("HOLD_HTMPK_SWITCH_UNQUALIFIED", 2, False, derived)

    reasons.append(
        f"Qualified {construct_id} dividing-cell containment switch under clinical AZT PK "
        f"({float(peak_uM):.2f} uM x {float(days):.0f} d, L95={float(l95_log10):.2f} log10 across {n_plated:,} cells/arm, "
        "mature beta spared). Remains dividing-escape containment only (never a post-mitotic whole-graft substitute)."
    )
    return _res("PASS_GATE33_HTMPK_DIVIDING_SWITCH_QUALIFIED", 0, True, derived)


def _build_valid_obs(construct_id: str = "DESIGN_Y_CLYBL_CDK1P_HTMPK_F105Y") -> Dict[str, Any]:
    return {
        "promoter_construct_id": construct_id,
        "claimed_as_postmitotic_whole_graft_substitute": False,
        "clinical_azt_pk_arm": {
            "certifying_azt_peak_uM": 5.0,
            "exposure_duration_days": 7.0,
            "intracellular_azt_mp_tp_lcms_verified": True,
        },
        "clonogenic_kill_assay": {
            "assay_modality": "CLONOGENIC_LIMITING_DILUTION_OUTGROWTH",
            "n_clonogenic_cells_plated_per_arm": 1_000_000,
            "l95_log10_dividing_kill": 4.35,
            "zero_post_washout_colony_rebound": True,
            "matched_10nM_ap1903_icasp9_comparator_included": True,
        },
        "mature_beta_bystander_and_mito_safety": {
            "mature_beta_viability_l95_pct": 93.5,
            "mature_beta_gsis_retention_l95_pct": 91.2,
            "mitochondrial_dttp_safety_check_passed": True,
        },
    }


def run_gate33_decision_table_self_tests() -> Dict[str, Any]:
    """Run 10 deterministic fail-closed self-tests on evaluate_gate33_htmpk_azt_switch."""
    r_pass_y = evaluate_gate33_htmpk_azt_switch(_build_valid_obs("DESIGN_Y_CLYBL_CDK1P_HTMPK_F105Y"))
    r_pass_d = evaluate_gate33_htmpk_azt_switch(_build_valid_obs("DESIGN_D_CLYBL_404BP_CDK1_300_HTMPK_F105Y"))

    # 3. Claiming post-mitotic whole-graft substitution -> FAIL_GY002 (exit 3)
    o_pm = _build_valid_obs()
    o_pm["claimed_as_postmitotic_whole_graft_substitute"] = True
    r_pm = evaluate_gate33_htmpk_azt_switch(o_pm)

    # 4. Supraphysiologic 100 uM static AZT only -> HOLD_SUPRAPHYSIOLOGIC
    o_hi = _build_valid_obs()
    o_hi["clinical_azt_pk_arm"]["certifying_azt_peak_uM"] = 100.0
    r_hi = evaluate_gate33_htmpk_azt_switch(o_hi)

    # 5. Flow cytometry only -> HOLD_INSUFFICIENT_CLONOGENIC_DYNAMIC_RANGE
    o_flow = _build_valid_obs()
    o_flow["clonogenic_kill_assay"]["assay_modality"] = "ANNEXIN_V_FLOW_CYTOMETRY"
    r_flow = evaluate_gate33_htmpk_azt_switch(o_flow)

    # 6. Underpowered clonogenic count (< 10^6) -> HOLD_INSUFFICIENT_CLONOGENIC_DYNAMIC_RANGE
    o_small = _build_valid_obs()
    o_small["clonogenic_kill_assay"]["n_clonogenic_cells_plated_per_arm"] = 50_000
    r_small = evaluate_gate33_htmpk_azt_switch(o_small)

    # 7. Sub-4-log10 kill (reproducing Marin-like incomplete clearance) -> HOLD_HTMPK_SWITCH_UNQUALIFIED, primary iCasp9 unaffected!
    o_low = _build_valid_obs()
    o_low["clonogenic_kill_assay"]["l95_log10_dividing_kill"] = 1.8
    r_low = evaluate_gate33_htmpk_azt_switch(o_low)

    # 8. Mature beta-cell bystander / mitochondrial toxicity -> HOLD_BYSTANDER_OR_MITOCHONDRIAL_BETA_TOXICITY
    o_byst = _build_valid_obs()
    o_byst["mature_beta_bystander_and_mito_safety"]["mature_beta_gsis_retention_l95_pct"] = 72.0
    r_byst = evaluate_gate33_htmpk_azt_switch(o_byst)

    # 9. Unrecognized / conflated promoter construct ID -> HOLD_INVALID_OR_MISSING_INPUT
    o_bad_p = _build_valid_obs("GENERIC_HTMPK_POOLED")
    r_bad_p = evaluate_gate33_htmpk_azt_switch(o_bad_p)

    # 10. Strict JSON NaN & duplicate-key rejection + universal invariants
    nan_rej = False
    try:
        load_strict_json_text('{"x": NaN}', "nan_probe")
    except StrictJsonError:
        nan_rej = True
    dup_rej = False
    try:
        load_strict_json_text('{"a": 1, "a": 2}', "dup_probe")
    except StrictJsonError:
        dup_rej = True

    all_res = [r_pass_y, r_pass_d, r_pm, r_hi, r_flow, r_small, r_low, r_byst, r_bad_p]
    cases = {
        "01_design_y_cdk1p_clinical_pk_clonogenic_pass": (
            r_pass_y["verdict"] == "PASS_GATE33_HTMPK_DIVIDING_SWITCH_QUALIFIED"
            and r_pass_y["exit_code"] == 0
            and r_pass_y["chr13_backup_switch_qualified"] is True
            and r_pass_y["postmitotic_whole_graft_substitute_authorized"] is False
        ),
        "02_design_d_cdk1_300_separate_promoter_pass": (
            r_pass_d["verdict"] == "PASS_GATE33_HTMPK_DIVIDING_SWITCH_QUALIFIED"
            and r_pass_d["exit_code"] == 0
            and r_pass_d["chr13_backup_switch_qualified"] is True
        ),
        "03_postmitotic_substitute_claim_hard_blocks_gy002": (
            r_pm["verdict"] == "FAIL_GY002_POSTMITOTIC_SCOPE_VIOLATION"
            and r_pm["exit_code"] == 3
            and r_pm["chr13_backup_switch_qualified"] is False
        ),
        "04_supraphysiologic_100uM_azt_only_emits_hold": (
            r_hi["verdict"] == "HOLD_SUPRAPHYSIOLOGIC_AZT_ONLY_NOT_CLINICAL_PK"
            and r_hi["exit_code"] == 2
        ),
        "05_flow_cytometry_only_rejected_insufficient_dynamic_range": (
            r_flow["verdict"] == "HOLD_INSUFFICIENT_CLONOGENIC_DYNAMIC_RANGE"
            and r_flow["exit_code"] == 2
        ),
        "06_underpowered_50k_clonogenic_arm_rejected": (
            r_small["verdict"] == "HOLD_INSUFFICIENT_CLONOGENIC_DYNAMIC_RANGE"
            and r_small["exit_code"] == 2
        ),
        "07_sub_4log_kill_holds_chr13_preserving_primary_aavs1_icasp9": (
            r_low["verdict"] == "HOLD_HTMPK_SWITCH_UNQUALIFIED"
            and r_low["exit_code"] == 2
            and r_low["chr13_backup_switch_qualified"] is False
            and r_low["primary_aavs1_icasp9_gate_unaffected"] is True
        ),
        "08_mature_beta_bystander_or_mito_toxicity_emits_hold": (
            r_byst["verdict"] == "HOLD_BYSTANDER_OR_MITOCHONDRIAL_BETA_TOXICITY"
            and r_byst["exit_code"] == 2
        ),
        "09_conflated_generic_promoter_id_rejected": (
            r_bad_p["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_bad_p["exit_code"] == 2
        ),
        "10_strict_json_and_universal_scope_and_primary_switch_invariants": (
            nan_rej
            and dup_rej
            and all(r["postmitotic_whole_graft_substitute_authorized"] is False for r in all_res)
            and all(r["primary_aavs1_icasp9_gate_unaffected"] is True for r in all_res)
        ),
    }
    if not all(cases.values()):
        failed = [k for k, v in cases.items() if not v]
        raise RuntimeError(f"Gate 33 self-tests failed: {failed}")
    return {
        "total_cases": len(cases),
        "all_passed": True,
        "universal_never_postmitotic_substitute_invariant": True,
        "universal_primary_icasp9_unaffected_invariant": True,
        "cases": cases,
    }


def audit_playbook_gy002_and_blueprint_sync(repo_root: Path) -> Dict[str, Any]:
    pb = (repo_root / PLAYBOOK_REL).read_text(encoding="utf-8")
    bp = (repo_root / BLUEPRINT_REL).read_text(encoding="utf-8")
    g0v = (repo_root / GATE0V_REL).read_text(encoding="utf-8")
    gy = load_strict_json_file(repo_root / GRAVEYARD_REL)
    dt = load_strict_json_file(repo_root / DECISION_TREE_REL)

    gy2 = next(
        (e for e in gy.get("graveyard_entries", []) if e.get("graveyard_id") == "GRAVEYARD_002_LINEAGE_RESTRICTED_G6PC2_OR_INS_ICASP9_SUICIDE_SWITCH"),
        None,
    )
    if gy2 is None:
        raise RuntimeError("GRAVEYARD_002 entry missing")
    gy2_blob = json.dumps(gy2, ensure_ascii=False)
    gy2_synced = all(
        tok in gy2_blob
        for tok in ("IIP-0051", "GATE-33", "hTMPK-F105Y", "never a post-mitotic whole-graft erasability substitute", "23186165", "10390227", "15371631")
    )
    bp_synced = all(
        tok in bp
        for tok in ("IIP-0051", "GATE-33", "hTMPK-F105Y", "Design Y-FullStack v2", "D1b-Auto-C v2", "23186165")
    )
    dt_blk = dt.get(DECISION_TREE_KEY)
    dt_synced = isinstance(dt_blk, dict) and dt_blk.get("gate_id") == GATE_ID and dt_blk.get("contribution_id") == CONTRIBUTION_ID

    return {
        "playbook_has_tyms_postmitotic_caveat": "never a post-mitotic whole-graft erasability substitute" in pb,
        "gate0v_is_ap1903_panlineage_only_confirmed": ("AZT" not in g0v and "hTMPK" not in g0v),
        "gy002_severity_preserved": gy2.get("severity_level") == "BLOCK",
        "gy002_grid_entry_count": len(gy.get("graveyard_entries", [])),
        "offgrid_guardrail_count": len(gy.get("off_grid_molecular_dead_end_guardrails", {}).get("guardrails", [])),
        "gy002_iip0051_addendum_synced": gy2_synced,
        "blueprint_design_y_d_and_htmpk_synced": bp_synced,
        "decision_tree_gate33_block_synced": dt_synced,
    }


def build_verification_report(repo_root: Path) -> Dict[str, Any]:
    pin_checks: Dict[str, Dict[str, Any]] = {}
    for rel, expected in FROZEN_SHA256_PINS.items():
        actual = sha256_file(repo_root / rel)
        pin_checks[rel] = {
            "expected_sha256": expected,
            "actual_sha256": actual,
            "matched": actual == expected,
        }
        if actual != expected:
            raise RuntimeError(f"Frozen SHA-256 pin mismatch for {rel}: {actual} != {expected}")

    pb_sha = _extract_playbook_sec4120_sha256(repo_root / PLAYBOOK_REL)
    if pb_sha != EXPECTED_PLAYBOOK_SEC4120_SHA256:
        raise RuntimeError(f"Playbook sec 4.1.20 SHA-256 mismatch: {pb_sha} != {EXPECTED_PLAYBOOK_SEC4120_SHA256}")

    sc = load_strict_json_file(repo_root / SIDE_CONTRACT_REL)
    if sc.get("gate_id") != GATE_ID or sc.get("contribution_id") != CONTRIBUTION_ID:
        raise RuntimeError("Side contract gate_id/contribution_id mismatch")

    pk_anchors = compute_azt_pk_and_clonogenic_anchors()
    self_tests = run_gate33_decision_table_self_tests()
    audit = audit_playbook_gy002_and_blueprint_sync(repo_root)

    if not (
        audit["playbook_has_tyms_postmitotic_caveat"]
        and audit["gate0v_is_ap1903_panlineage_only_confirmed"]
        and audit["gy002_severity_preserved"]
        and audit["gy002_iip0051_addendum_synced"]
        and audit["blueprint_design_y_d_and_htmpk_synced"]
        and audit["decision_tree_gate33_block_synced"]
    ):
        raise RuntimeError(f"Audit check failed: {audit}")

    return {
        "schema_version": "iip0051_htmpk_azt_switch_verification_v0.8.0",
        "contribution_id": CONTRIBUTION_ID,
        "decision_id": DECISION_ID,
        "gate_id": GATE_ID,
        "gate_alias": GATE_ALIAS,
        "generated_date": GENERATED_DATE,
        "live_headline_delta_pp_today": 0.0,
        "zero_lims_touch_and_frozen_pins": {
            "all_pins_matched": True,
            "playbook_sec4120_sha256_matched": True,
            "pins": pin_checks,
        },
        "clinical_azt_pk_and_clonogenic_anchors": pk_anchors,
        "gate33_decision_table_self_tests": self_tests,
        "cross_document_and_graveyard_audit": audit,
        "all_checks_passed": True,
    }


def main(argv: Optional[List[str]] = None) -> int:
    parser = argparse.ArgumentParser(description="IIP-0051 / Gate 33 hTMPK-F105Y/AZT switch verifier and evaluator")
    parser.add_argument("--repo-root", type=Path, default=REPO_ROOT)
    parser.add_argument("--output", type=Path, default=None, help="Write deterministic verification JSON receipt")
    parser.add_argument("--check", action="store_true", help="Verify on-disk receipt matches recomputed output")
    parser.add_argument("--evaluate-azt-switch", type=Path, default=None, help="Evaluate a Stage-0 Gate 33 JSON payload")
    args = parser.parse_args(argv)

    if args.evaluate_azt_switch is not None:
        try:
            obs = load_strict_json_file(args.evaluate_azt_switch)
        except Exception as exc:
            err_out = {
                "gate_id": GATE_ID,
                "gate_alias": GATE_ALIAS,
                "verdict": "HOLD_INVALID_OR_MISSING_INPUT",
                "exit_code": 2,
                "chr13_backup_switch_qualified": False,
                "postmitotic_whole_graft_substitute_authorized": False,
                "primary_aavs1_icasp9_gate_unaffected": True,
                "reasons": [f"Strict JSON parse failure: {exc}"],
                "derived_summary": {},
            }
            print(json.dumps(err_out, indent=2, ensure_ascii=False))
            return 2
        res = evaluate_gate33_htmpk_azt_switch(obs)
        print(json.dumps(res, indent=2, ensure_ascii=False))
        return int(res["exit_code"])

    report = build_verification_report(args.repo_root)
    rendered = json.dumps(report, indent=2, ensure_ascii=False) + "\n"

    if args.output is not None:
        args.output.parent.mkdir(parents=True, exist_ok=True)
        args.output.write_text(rendered, encoding="utf-8")
        print(f"Wrote {args.output} (all_checks_passed={report['all_checks_passed']})")
        return 0

    if args.check:
        target = args.repo_root / VERIFICATION_REL
        if not target.is_file():
            print(f"ERROR: Missing receipt {target}", file=sys.stderr)
            return 1
        actual = target.read_text(encoding="utf-8")
        if actual != rendered:
            print(f"ERROR: On-disk receipt {target} drifts from recomputed output", file=sys.stderr)
            return 1
        print(
            f"PASS: {target.name} byte-exact | cmax={report['clinical_azt_pk_and_clonogenic_anchors']['human_300mg_cmax_alone_uM']} uM "
            f"| self_tests={report['gate33_decision_table_self_tests']['total_cases']}/{report['gate33_decision_table_self_tests']['total_cases']}"
        )
        return 0

    print(rendered)
    return 0


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