#!/usr/bin/env python3
"""
Standalone Zero-LIMS-Touch Executable Verifier for IIP-0059 / DEC-140 / GATE-38:
Five-Transgene 72-h Hypoxic ISR Joint Coverage, Fréchet/Copula Reconciliation,
f_ISR Floor Trajectory Grid, Empirical Marginal/Dependence/sigma_ln Audit, and
Wave-6 Arm Scoping.

Zero wetlab_contract.py imports; zero mutations to frozen LIMS contracts, FASTAs,
or live published 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" / "iip0059_five_transgene_joint_coverage_side_contract_v0.9.0.json"
)
DEFAULT_RECEIPT_PATH = (
    ROOT / "data" / "extracted" / "iip0059_five_transgene_joint_coverage_verification_v0.9.0.json"
)

CRIT_95_MULT = 1.644854
DEFAULT_JOINT_SE = 0.01
JOINT_MIN_FRAC = 0.90
OPERATIONAL_SIGMA_LN_MAX = 0.28
Z_P10 = -1.2815515655446004
Z_P02 = -2.0537489106318230

DECAY_HALF_LIVES_H = {
    "CD47_IgV_GPI": 20.0,
    "HLAE_SCT": 14.0,
    "PDL1": 16.0,
    "SERPINB9": 6.0,
    "iCasp9": 24.0,
}
THRESHOLDS = {
    "CD47_IgV_GPI": 180000.0,
    "HLAE_SCT": 15000.0,
    "PDL1": 5000.0,
    "SERPINB9": 0.30,
    "iCasp9": 0.05,
}


def norm_cdf(x: float) -> float:
    return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0)))


def norm_ppf(p: float) -> float:
    p_clamped = min(max(p, 1e-12), 1.0 - 1e-12)
    lo, hi = -8.0, 8.0
    for _ in range(80):
        mid = 0.5 * (lo + hi)
        if norm_cdf(mid) < p_clamped:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def decay_72h(hour0_mean: float, f_isr: float, t_half_h: float) -> float:
    return hour0_mean * (f_isr + (1.0 - f_isr) * (2.0 ** (-72.0 / t_half_h)))


def lognormal_p10(mean_val: float, sigma_ln: float) -> float:
    mu = math.log(mean_val) - 0.5 * sigma_ln * sigma_ln
    return math.exp(mu + Z_P10 * sigma_ln)


def lognormal_prob_ge(mean_val: float, sigma_ln: float, threshold: float) -> float:
    mu = math.log(mean_val) - 0.5 * sigma_ln * sigma_ln
    return 1.0 - norm_cdf((math.log(threshold) - mu) / sigma_ln)


def required_hour0_mean(
    threshold: float, f_isr: float, t_half_h: float, sigma_ln: float, z_quantile: float
) -> float:
    req_72h_mean = threshold * math.exp(0.5 * sigma_ln * sigma_ln - z_quantile * sigma_ln)
    retention = f_isr + (1.0 - f_isr) * (2.0 ** (-72.0 / t_half_h))
    return req_72h_mean / retention


def frechet_bounds(marginals: list[float]) -> dict[str, float]:
    k = len(marginals)
    lo = max(0.0, sum(marginals) - (k - 1))
    indep = 1.0
    for p in marginals:
        indep *= p
    hi = min(marginals) if marginals else 0.0
    return {
        "frechet_lower": round(lo, 8),
        "independent_product": round(indep, 8),
        "frechet_upper": round(hi, 8),
    }


def equicorrelated_gaussian_copula_joint(marginals: list[float], rho: float, steps: int = 800) -> float:
    if not marginals:
        return 0.0
    if rho >= 1.0:
        return min(marginals)
    if rho <= 0.0:
        prod = 1.0
        for p in marginals:
            prod *= p
        return prod
    zs = [norm_ppf(p) for p in marginals]
    sr = math.sqrt(rho)
    s1 = math.sqrt(1.0 - rho)
    a, b = -8.0, 8.0
    h = (b - a) / steps
    total = 0.0
    inv_sqrt_2pi = 1.0 / math.sqrt(2.0 * math.pi)
    for idx in range(steps):
        g = a + (idx + 0.5) * h
        w = math.exp(-0.5 * g * g) * inv_sqrt_2pi * h
        p_cond = 1.0
        for z in zs:
            p_cond *= norm_cdf((z + sr * g) / s1)
        total += w * p_cond
    return total


def build_trajectory_and_copula_audit() -> dict[str, Any]:
    """Compute complete f_ISR x sigma_ln Hour-0 requirements and Gaussian-copula stress table."""
    hour0_grid = []
    for f_isr in (0.50, 0.75, 0.85):
        for sigma_ln in (0.28, 0.32, 0.45):
            hour0_grid.append(
                {
                    "f_isr": f_isr,
                    "sigma_ln": sigma_ln,
                    "cd47_hour0_min_for_72h_p10": round(
                        required_hour0_mean(THRESHOLDS["CD47_IgV_GPI"], f_isr, 20.0, sigma_ln, Z_P10), 1
                    ),
                    "cd47_hour0_min_for_72h_p02": round(
                        required_hour0_mean(THRESHOLDS["CD47_IgV_GPI"], f_isr, 20.0, sigma_ln, Z_P02), 1
                    ),
                    "hlae_hour0_min_for_72h_p10": round(
                        required_hour0_mean(THRESHOLDS["HLAE_SCT"], f_isr, 14.0, sigma_ln, Z_P10), 1
                    ),
                    "hlae_hour0_min_for_72h_p02": round(
                        required_hour0_mean(THRESHOLDS["HLAE_SCT"], f_isr, 14.0, sigma_ln, Z_P02), 1
                    ),
                }
            )

    def _lot_marginals(cd47_h0: float, hlae_h0: float, f_isr: float, sigma_ln: float) -> list[float]:
        return [
            lognormal_prob_ge(decay_72h(cd47_h0, f_isr, 20.0), sigma_ln, THRESHOLDS["CD47_IgV_GPI"]),
            lognormal_prob_ge(decay_72h(hlae_h0, f_isr, 14.0), sigma_ln, THRESHOLDS["HLAE_SCT"]),
            lognormal_prob_ge(decay_72h(45000.0, f_isr, 16.0), sigma_ln, THRESHOLDS["PDL1"]),
            lognormal_prob_ge(decay_72h(0.89, f_isr, 6.0), sigma_ln, THRESHOLDS["SERPINB9"]),
            0.99,  # Prospective iCasp9 assumption pending Hour-0 uM calibration
        ]

    copula_cases = {
        "five_equal_p10_0p90": [0.90] * 5,
        "five_equal_p02_0p98": [0.98] * 5,
        "atlas_min_qualifying_lot_320k_26144_f0p85_s0p28": _lot_marginals(320000.0, 26144.0, 0.85, 0.28),
        "upper_remediated_lot_366k_32k_f0p85_s0p28": _lot_marginals(366000.0, 32000.0, 0.85, 0.28),
        "remediated_lot_at_f_isr_0p50_floor_366k_32k_s0p28": _lot_marginals(366000.0, 32000.0, 0.50, 0.28),
    }

    copula_summary: dict[str, Any] = {}
    min_pt = JOINT_MIN_FRAC + CRIT_95_MULT * DEFAULT_JOINT_SE
    for name, margs in copula_cases.items():
        bounds = frechet_bounds(margs)
        by_rho = {
            f"rho_{rho:.2f}": round(equicorrelated_gaussian_copula_joint(margs, rho), 6)
            for rho in (0.0, 0.25, 0.50, 0.75, 0.90, 1.0)
        }
        copula_summary[name] = {
            "marginals": [round(x, 6) for x in margs],
            **bounds,
            "gaussian_copula_joint": by_rho,
            "clears_lower95_at_default_se_under_rho_0p00": by_rho["rho_0.00"] >= min_pt,
            "clears_lower95_at_default_se_under_rho_1p00": by_rho["rho_1.00"] >= min_pt,
        }

    return {
        "min_point_estimate_for_lower95_at_default_se": round(min_pt, 8),
        "hour0_requirement_grid_f_isr_x_sigma_ln": hour0_grid,
        "copula_and_frechet_stress_table": copula_summary,
    }


def evaluate_gate38_lot(record: dict[str, Any], side_contract: dict[str, Any]) -> dict[str, Any]:
    """Fail-closed evaluation of a Stage-0 72-h hypoxic joint-coverage lot record."""
    reasons: list[str] = []
    warnings: list[str] = []

    product_id = record.get("product_id")
    arm_table = side_contract["arm_scoping_table"]
    if product_id not in arm_table:
        return {
            "verdict": "HOLD_UNDECLARED_PRODUCT_SCOPE",
            "pass": False,
            "reasons": [f"Undeclared product_id {product_id!r}; must match Gate 38 arm_scoping_table."],
            "warnings": [],
        }

    arm_spec = arm_table[product_id]
    active_axes: list[str] = arm_spec["active_axes"]

    # 1. Anti-escalation guard (GY-018 / IIP-0047): forbid blind p02 CD47 floor escalation
    if record.get("blind_p02_cd47_escalation_requested") is True:
        reasons.append(
            "BLOCK_GY018_BLIND_P02_CD47_ESCALATION: Raising CD47 floor to p02 without hypoxic TSP-1/UPR ceiling qualification is prohibited (IIP-0047 / OQ-008)."
        )

    # 2. Stress-regime matching
    allowed_regimes = set(side_contract["stress_regime_matching_rule"]["allowed_matched_regimes"])
    joint_regime = record.get("obs_hypoxic_72h_stress_o2_regime")
    marginal_regime = record.get("obs_hypoxic_72h_marginal_stress_o2_regime", joint_regime)
    if joint_regime not in allowed_regimes:
        reasons.append(f"HOLD_UNDECLARED_STRESS_REGIME: {joint_regime!r} not in allowed matched O2 regimes.")
    elif marginal_regime != joint_regime:
        reasons.append(
            f"HOLD_CROSS_REGIME_MISMATCH: marginal regime {marginal_regime!r} != joint regime {joint_regime!r}."
        )

    # 3. Calibration chain provenance for every active axis (especially SERPINB9 uM & iCasp9 Hour-0 uM)
    cal_chains = record.get("obs_hypoxic_72h_calibration_chains_verified") or {}
    for axis in active_axes:
        if cal_chains.get(axis) is not True:
            reasons.append(f"HOLD_UNVERIFIED_CALIBRATION_CHAIN: axis {axis} lacks verified calibration chain.")

    # 4. Empirical marginals & Fréchet consistency
    marginals_map = record.get("obs_hypoxic_72h_per_axis_marginals_above_threshold") or {}
    missing_axes = [ax for ax in active_axes if ax not in marginals_map or marginals_map[ax] is None]
    if missing_axes:
        reasons.append(f"HOLD_MISSING_PER_AXIS_MARGINALS: missing {missing_axes}.")

    p_joint = record.get("obs_hypoxic_72h_joint_above_threshold_fraction")
    se_joint = record.get("obs_hypoxic_72h_joint_above_threshold_se")
    if not isinstance(p_joint, (int, float)) or not (0.0 <= float(p_joint) <= 1.0):
        reasons.append("HOLD_INVALID_JOINT_FRACTION: obs_hypoxic_72h_joint_above_threshold_fraction missing or out of [0,1].")
    if not isinstance(se_joint, (int, float)) or float(se_joint) <= 0.0:
        reasons.append("HOLD_MISSING_EXPLICIT_SE: explicit positive SE required for joint fraction.")

    # 5. Empirical sigma_ln observation
    sigma_map = record.get("obs_hypoxic_72h_sigma_ln_by_axis") or {}
    for ax in ("CD47_IgV_GPI", "HLAE_SCT"):
        if ax in active_axes:
            s_val = sigma_map.get(ax)
            if not isinstance(s_val, (int, float)) or float(s_val) <= 0.0:
                reasons.append(f"HOLD_MISSING_OBSERVED_SIGMA_LN: observed sigma_ln required for active axis {ax}.")
            elif float(s_val) > OPERATIONAL_SIGMA_LN_MAX:
                warnings.append(
                    f"SIGMA_LN_ABOVE_OPERATIONAL_TARGET: {ax} sigma_ln={float(s_val):.3f} > {OPERATIONAL_SIGMA_LN_MAX:.2f}."
                )

    # 6. f_ISR floor & scrap-risk warning
    f_isr = record.get("obs_hypoxic_15mmhg_f_isr_translation_ratio")
    if not isinstance(f_isr, (int, float)) or float(f_isr) < 0.50:
        reasons.append("HOLD_F_ISR_BELOW_0P50_FLOOR: obs_hypoxic_15mmhg_f_isr_translation_ratio < 0.50.")
    elif float(f_isr) < 0.75:
        warnings.append(
            f"F_ISR_IN_SCRAP_RISK_BAND: observed f_ISR={float(f_isr):.3f} in [0.50, 0.75); below atlas clearing trajectory band [0.75, 0.85]."
        )

    diagnostics: dict[str, Any] = {"arm_scope": arm_spec["scope"], "active_axes": active_axes}
    if not missing_axes and isinstance(p_joint, (int, float)) and isinstance(se_joint, (int, float)):
        marg_vals = [float(marginals_map[ax]) for ax in active_axes]
        if any(not (0.0 <= v <= 1.0) for v in marg_vals):
            reasons.append("HOLD_INVALID_MARGINAL_RANGE: marginal fraction outside [0, 1].")
        else:
            bounds = frechet_bounds(marg_vals)
            pj = float(p_joint)
            lower95 = pj - CRIT_95_MULT * float(se_joint)
            diagnostics.update(bounds)
            diagnostics["observed_joint"] = round(pj, 6)
            diagnostics["observed_lower95"] = round(lower95, 6)

            # Same-event mathematical impossibility check
            if pj > bounds["frechet_upper"] + 1e-9 or pj < bounds["frechet_lower"] - 1e-9:
                reasons.append(
                    f"FAIL_IMPOSSIBLE_FRECHET_VIOLATION: joint={pj:.6f} outside [{bounds['frechet_lower']:.6f}, {bounds['frechet_upper']:.6f}]."
                )
            else:
                denom = bounds["frechet_upper"] - bounds["independent_product"]
                if denom > 1e-9:
                    diagnostics["empirical_dependence_index"] = round(
                        (pj - bounds["independent_product"]) / denom, 6
                    )
                else:
                    diagnostics["empirical_dependence_index"] = None

            if pj < JOINT_MIN_FRAC or lower95 < JOINT_MIN_FRAC:
                reasons.append(
                    f"FAIL_JOINT_GATE_BELOW_0P90: joint={pj:.6f}, lower95={lower95:.6f} < 0.90."
                )

    passed = len(reasons) == 0
    return {
        "verdict": "PASS_GATE38_JOINT_COVERAGE_AND_DEPENDENCE" if passed else reasons[0].split(":")[0],
        "pass": passed,
        "reasons": reasons,
        "warnings": warnings,
        "diagnostics": diagnostics,
    }


def run_self_tests(side_contract: dict[str, Any]) -> list[dict[str, Any]]:
    """Run 11 deterministic adversarial self-tests covering math, scoping, and fail-closed guards."""
    results: list[dict[str, Any]] = []
    audit = build_trajectory_and_copula_audit()
    cop = audit["copula_and_frechet_stress_table"]

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

    # T1: Exact p10 / p02 Fréchet & independence arithmetic
    t1 = (
        math.isclose(cop["five_equal_p10_0p90"]["independent_product"], 0.59049, abs_tol=1e-7)
        and math.isclose(cop["five_equal_p10_0p90"]["frechet_lower"], 0.50, abs_tol=1e-7)
        and math.isclose(cop["five_equal_p02_0p98"]["frechet_lower"], 0.90, abs_tol=1e-7)
        and math.isclose(cop["five_equal_p02_0p98"]["independent_product"], 0.9039208, abs_tol=1e-6)
    )
    _rec("T01_exact_frechet_and_independence_identities", t1, "0.9^5=0.59049, p10_lo=0.50, p02_lo=0.90")

    # T2: Minimum qualifying lot (320k / 26,144) cannot clear lower95 >= 0.90 even at rho=1.0
    m_min = cop["atlas_min_qualifying_lot_320k_26144_f0p85_s0p28"]
    t2 = (
        math.isclose(m_min["frechet_upper"], 0.90000, abs_tol=1e-4)
        and not m_min["clears_lower95_at_default_se_under_rho_1p00"]
    )
    _rec("T02_min_qualifying_lot_fails_lower95_in_expectation", t2, f"upper={m_min['frechet_upper']}")

    # T3: Upper remediated lot (366k / 32k, f=0.85, s=0.28) clears lower95 even at rho=0.0
    m_up = cop["upper_remediated_lot_366k_32k_f0p85_s0p28"]
    t3 = m_up["clears_lower95_at_default_se_under_rho_0p00"] and m_up["gaussian_copula_joint"]["rho_0.00"] > 0.93
    _rec("T03_upper_remediated_lot_clears_even_under_independence", t3, f"rho0={m_up['gaussian_copula_joint']['rho_0.00']}")

    # T4: Same upper remediated lot collapses at f_ISR=0.50 floor
    m_f50 = cop["remediated_lot_at_f_isr_0p50_floor_366k_32k_s0p28"]
    t4 = m_f50["frechet_upper"] < 0.60 and m_f50["gaussian_copula_joint"]["rho_0.00"] < 0.35
    _rec("T04_f_isr_0p50_floor_collapse_verified", t4, f"rho0={m_f50['gaussian_copula_joint']['rho_0.00']}, hi={m_f50['frechet_upper']}")

    base_pass_lot = {
        "product_id": "ISLET1_DESIGN_A_V080_REF",
        "obs_hypoxic_72h_joint_above_threshold_fraction": 0.945,
        "obs_hypoxic_72h_joint_above_threshold_se": 0.008,
        "obs_hypoxic_72h_per_axis_marginals_above_threshold": {
            "CD47_IgV_GPI": 0.968,
            "HLAE_SCT": 0.977,
            "PDL1": 0.999,
            "SERPINB9": 0.998,
            "iCasp9": 0.990,
        },
        "obs_hypoxic_72h_sigma_ln_by_axis": {"CD47_IgV_GPI": 0.26, "HLAE_SCT": 0.25},
        "obs_hypoxic_72h_stress_o2_regime": "72h_2pct_O2_15mmHg_16p7mM_glc_cytokines_DEC050_052",
        "obs_hypoxic_72h_marginal_stress_o2_regime": "72h_2pct_O2_15mmHg_16p7mM_glc_cytokines_DEC050_052",
        "obs_hypoxic_72h_calibration_chains_verified": {
            "CD47_IgV_GPI": True,
            "HLAE_SCT": True,
            "PDL1": True,
            "SERPINB9": True,
            "iCasp9": True,
        },
        "obs_hypoxic_15mmhg_f_isr_translation_ratio": 0.85,
    }

    # T5: Valid Arm A lot passes with empirical dependence index computed
    r5 = evaluate_gate38_lot(base_pass_lot, side_contract)
    _rec("T05_valid_arm_a_lot_passes", r5["pass"] and r5["diagnostics"]["empirical_dependence_index"] is not None, r5["verdict"])

    # T6: Impossible joint > min(marginals) rejected fail-closed
    bad_frechet = dict(base_pass_lot, obs_hypoxic_72h_joint_above_threshold_fraction=0.985)
    r6 = evaluate_gate38_lot(bad_frechet, side_contract)
    _rec("T06_impossible_frechet_violation_rejected", not r6["pass"] and "FRECHET" in r6["verdict"], r6["verdict"])

    # T7: Cross-regime mismatch (2% marginals vs 1% joint) rejected
    bad_regime = dict(
        base_pass_lot, obs_hypoxic_72h_stress_o2_regime="72h_1pct_O2_16p7mM_glc_cytokines_DEC053"
    )
    r7 = evaluate_gate38_lot(bad_regime, side_contract)
    _rec("T07_cross_regime_o2_mismatch_rejected", not r7["pass"] and "CROSS_REGIME" in r7["verdict"], r7["verdict"])

    # T8: Missing iCasp9 calibration chain rejected
    bad_cal = dict(
        base_pass_lot,
        obs_hypoxic_72h_calibration_chains_verified={
            **base_pass_lot["obs_hypoxic_72h_calibration_chains_verified"],
            "iCasp9": False,
        },
    )
    r8 = evaluate_gate38_lot(bad_cal, side_contract)
    _rec("T08_missing_icasp9_calibration_chain_rejected", not r8["pass"] and "CALIBRATION" in r8["verdict"], r8["verdict"])

    # T9: Missing sigma_ln rejected
    bad_sig = dict(base_pass_lot, obs_hypoxic_72h_sigma_ln_by_axis={"CD47_IgV_GPI": 0.26})
    r9 = evaluate_gate38_lot(bad_sig, side_contract)
    _rec("T09_missing_observed_sigma_ln_rejected", not r9["pass"] and "SIGMA_LN" in r9["verdict"], r9["verdict"])

    # T10: Blind p02 CD47 escalation blocked (GY-018 / IIP-0047)
    bad_p02 = dict(base_pass_lot, blind_p02_cd47_escalation_requested=True)
    r10 = evaluate_gate38_lot(bad_p02, side_contract)
    _rec("T10_blind_p02_cd47_escalation_blocked", not r10["pass"] and "GY018" in r10["verdict"], r10["verdict"])

    # T11: Arm D autologous 3-axis subset (PDL1, SERPINB9, iCasp8) passes WITHOUT requiring CD47/HLA-E/iCasp9
    arm_d_lot = {
        "product_id": "ISLET1_DESIGN_D1B_LEAN_K2",
        "obs_hypoxic_72h_joint_above_threshold_fraction": 0.968,
        "obs_hypoxic_72h_joint_above_threshold_se": 0.008,
        "obs_hypoxic_72h_per_axis_marginals_above_threshold": {
            "PDL1": 0.995,
            "SERPINB9": 0.992,
            "iCasp8": 0.975,
        },
        "obs_hypoxic_72h_sigma_ln_by_axis": {},
        "obs_hypoxic_72h_stress_o2_regime": "72h_2pct_O2_15mmHg_16p7mM_glc_cytokines_DEC050_052",
        "obs_hypoxic_72h_calibration_chains_verified": {
            "PDL1": True,
            "SERPINB9": True,
            "iCasp8": True,
        },
        "obs_hypoxic_15mmhg_f_isr_translation_ratio": 0.85,
    }
    r11 = evaluate_gate38_lot(arm_d_lot, side_contract)
    _rec("T11_arm_d_autologous_3axis_subset_scoped_cleanly", r11["pass"] and r11["diagnostics"]["arm_scope"] == "SUBSET_3_TRANSGENE_AUTOLOGOUS_ICASP8", r11["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-38 (IIP-0059 / DEC-140) five-transgene joint coverage & dependence 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"))
    audit = build_trajectory_and_copula_audit()
    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": "iip0059_five_transgene_joint_coverage_verification_v0.9.0",
        "gate_id": "GATE-38",
        "contribution_id": "IIP-0059",
        "decision_id": "DEC-140",
        "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,
        "quantitative_audit": audit,
    }

    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-38 (IIP-0059 / DEC-140) 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())
