#!/usr/bin/env python3
"""Clean-Room Standalone Offline Verifier for CAIN-42 Evolution 122 (FIRME AI CORPORATION).

ZERO CAIN imports — Python standard library ONLY.
Run as:
    python3 -I verify_e122_offline.py <bundle_dir>
"""
from __future__ import annotations

import ast
import hashlib
import json
import math
import pathlib
import sys
from typing import Any


def _sha256_file(path: pathlib.Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as fh:
        for chunk in iter(lambda: fh.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


def _exact_mcnemar(a: list[bool], b: list[bool]) -> dict[str, Any]:
    assert len(a) == len(b) and len(a) > 0
    b_wins = sum(1 for x, y in zip(a, b) if x and not y)
    c_losses = sum(1 for x, y in zip(a, b) if (not x) and y)
    n_disc = b_wins + c_losses
    if n_disc == 0:
        p = 1.0
    else:
        k = min(b_wins, c_losses)
        p = min(1.0, 2.0 * sum(math.comb(n_disc, i) for i in range(k + 1)) / (2.0 ** n_disc))
    gain = (sum(a) - sum(b)) / len(a)
    return {"a_only_wins": b_wins, "b_only_losses": c_losses, "gain": round(gain, 4), "p_value": round(p, 12)}


def _check_zero_cain_imports(self_path: pathlib.Path) -> tuple[bool, list[str]]:
    tree = ast.parse(self_path.read_text(encoding="utf-8"))
    bad = []
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            for alias in node.names:
                if alias.name == "cain" or alias.name.startswith("cain."):
                    bad.append(alias.name)
        elif isinstance(node, ast.ImportFrom):
            mod = node.module or ""
            if mod == "cain" or mod.startswith("cain."):
                bad.append(mod)
    return (len(bad) == 0, bad)


def verify_bundle(bundle_dir: pathlib.Path) -> tuple[bool, list[dict[str, Any]]]:
    checks: list[dict[str, Any]] = []

    def rec(cid: str, ok: bool, detail: str) -> None:
        checks.append({"id": cid, "ok": bool(ok), "detail": detail})

    # 1. Self clean-room AST audit
    clean_ok, bad_imp = _check_zero_cain_imports(pathlib.Path(__file__).resolve())
    rec("V01_zero_cain_imports", clean_ok, f"bad_imports={bad_imp}")

    # 2. Manifest & SHA-256 verification
    manifest_path = bundle_dir / "MANIFEST.json"
    results_path = bundle_dir / "results.json"
    rec("V02_manifest_present", manifest_path.exists(), str(manifest_path.name))
    rec("V03_results_present", results_path.exists(), str(results_path.name))
    if not (manifest_path.exists() and results_path.exists()):
        return False, checks

    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    results = json.loads(results_path.read_text(encoding="utf-8"))

    rec("V04_entity_canonical", results.get("entity") == "FIRME AI CORPORATION" and manifest.get("entity") == "FIRME AI CORPORATION", f"entity={results.get('entity')}")
    rec("V05_agi_not_achieved", results.get("agi_status") == "NOT ACHIEVED", f"agi_status={results.get('agi_status')}")
    rec("V06_manifest_files_nonempty", len(manifest.get("files", [])) >= 10, f"files={len(manifest.get('files', []))}")

    hash_mismatches = []
    for entry in manifest.get("files", []):
        rel = entry["path"]
        fp = bundle_dir / rel
        if not fp.exists():
            hash_mismatches.append(f"MISSING:{rel}")
        else:
            actual = _sha256_file(fp)
            if actual != entry["sha256"]:
                hash_mismatches.append(f"SHA_MISMATCH:{rel}")
    rec("V07_manifest_sha256_all_match", len(hash_mismatches) == 0, f"mismatches={hash_mismatches}")

    # 3. 18-Gate completeness & strict honesty checks
    gates = results.get("gates", {})
    expected_gates = [f"G{i:02d}" for i in range(1, 19)]
    rec("V08_all_18_gates_present", all(g in gates for g in expected_gates), f"present={len(gates)}/18")
    valid_statuses = {"PASS", "PARTIAL", "FAIL", "BLOCKED", "NOT_TESTED"}
    rec("V09_gate_statuses_valid", all(gates[g]["status"] in valid_statuses for g in expected_gates if g in gates), "valid statuses")

    phases = results.get("phases", {})
    p0 = phases.get("phase0_baseline", {})
    p1 = phases.get("phase1_neural_adapter", {})
    p2 = phases.get("phase2_neural_abstraction", {})
    p3 = phases.get("phase3_external_benchmarks", {})
    p4_11 = phases.get("phase4_and_11_capability_self_improve", {})
    p5 = phases.get("phase5_neural_causal_world_model", {})
    p6 = phases.get("phase6_research_3cycles", {})
    p7_10 = phases.get("phases_7_to_10", {})
    p12 = phases.get("phase12_governed_neural_execution", {})
    p13 = phases.get("phase13_mission_12h_neural", {})
    p14 = phases.get("phase14_multi_org_trust", {})
    p15 = phases.get("phase15_commercial", {})

    # Phase 0 checks
    rec("V10_phase0_e120_e121_nobody_verified",
        p0.get("g01_status") == "PASS"
        and p0.get("e120", {}).get("verifier_nobody", {}).get("passed") is True
        and p0.get("e121", {}).get("verifier_nobody", {}).get("passed") is True,
        f"e120={p0.get('e120', {}).get('verifier_nobody', {}).get('summary')} e121={p0.get('e121', {}).get('verifier_nobody', {}).get('summary')}")

    # Strict G02 honesty: cannot be PASS unless E120 12h truly elapsed >= 43200s
    m120 = p0.get("e120", {}).get("mission_12h", {})
    g02_status = gates.get("G02", {}).get("status")
    g02_honest = (g02_status != "PASS") or (m120.get("status_file_state") == "COMPLETED" and float(m120.get("elapsed_wall_s", 0)) >= 43200.0)
    rec("V11_g02_wallclock_honesty", g02_honest, f"G02={g02_status}, elapsed={m120.get('elapsed_wall_s')}")

    # Phase 1: Real local neural models & zero authority granted
    rec("V12_phase1_real_local_models",
        p1.get("g03_passed") is True and p1.get("discovery", {}).get("active_local_count", 0) >= 2,
        f"active_local={p1.get('discovery', {}).get('active_local_count')}")
    rec("V13_phase1_zero_authority_granted",
        p1.get("adapter_summary", {}).get("any_authority_granted") is False
        and all(pr.get("authority_granted") is False for pr in p1.get("live_probes", [])),
        "authority_granted=False across all probes")

    # Phase 2: Independent McNemar recomputation from raw 48-element arrays
    raw2 = p2.get("raw", {})
    full_raw = raw2.get("full_cain_neural_organism", [])
    sym_raw = raw2.get("e120_symbolic_frozen", [])
    alone_raw = raw2.get("neural_model_alone", [])
    epi_raw = raw2.get("neural_no_abstraction_episodic", [])
    one_raw = raw2.get("neural_no_memory_oneshot", [])

    rec("V14_phase2_raw_n48", all(len(x) == 48 for x in (full_raw, sym_raw, alone_raw, epi_raw, one_raw)), f"len={len(full_raw)}")
    if len(full_raw) == 48:
        mc_sym = _exact_mcnemar(full_raw, sym_raw)
        mc_alone = _exact_mcnemar(full_raw, alone_raw)
        mc_epi = _exact_mcnemar(full_raw, epi_raw)
        mc_one = _exact_mcnemar(full_raw, one_raw)
        rec("V15_phase2_recomputed_vs_e120_symbolic",
            mc_sym["gain"] >= 0.50 and mc_sym["p_value"] < 0.001 and abs(mc_sym["gain"] - p2["comparisons"]["full_vs_e120_symbolic"]["gain"]) < 1e-3,
            f"recomputed={mc_sym}")
        rec("V16_phase2_recomputed_vs_neural_alone",
            mc_alone["gain"] >= 0.40 and mc_alone["p_value"] < 0.001 and abs(mc_alone["gain"] - p2["comparisons"]["full_vs_neural_alone"]["gain"]) < 1e-3,
            f"recomputed={mc_alone}")
        rec("V17_phase2_recomputed_vs_episodic",
            mc_epi["gain"] >= 0.40 and mc_epi["p_value"] < 0.001 and abs(mc_epi["gain"] - p2["comparisons"]["full_vs_neural_no_abstraction"]["gain"]) < 1e-3,
            f"recomputed={mc_epi}")
        rec("V18_phase2_recomputed_vs_oneshot",
            mc_one["gain"] >= 0.15 and mc_one["p_value"] < 0.01 and abs(mc_one["gain"] - p2["comparisons"]["full_vs_oneshot"]["gain"]) < 1e-3,
            f"recomputed={mc_one}")
    rec("V19_phase2_overfit_rejected",
        bool(p2.get("overfit_lookup_table_rejected", [False])[0]) and p2.get("abstractions_synthesized_and_verified", 0) >= 10,
        f"verified={p2.get('abstractions_synthesized_and_verified')}, overfit={p2.get('overfit_lookup_table_rejected')}")
    rec("V20_phase2_real_llm_telemetry",
        p2.get("adapter_telemetry", {}).get("successful_calls", 0) >= 50
        and p2.get("adapter_telemetry", {}).get("any_authority_granted") is False,
        f"calls={p2.get('adapter_telemetry', {}).get('successful_calls')}")

    # Phase 3: External benchmarks (AMA-Bench + ARC-AGI-2 unmerged) + Real-source open-world Python repair
    ama = p3.get("amabench", {})
    arc = p3.get("arc_agi_2", {})
    rw = p3.get("real_source_open_world", {})
    rec("V21_phase3_amabench_real",
        ama.get("n_questions", 0) >= 20 and "MIT" in str(ama.get("license", "")) and len(ama.get("rows", [])) == ama.get("n_questions", -1),
        f"n={ama.get('n_questions')}, raw_tail={ama.get('raw_tail_mean_f1')}, cain_prov={ama.get('cain_provenance_mean_f1')}")
    rec("V22_phase3_arc_agi_2_real_unmerged",
        arc.get("n_tasks", 0) >= 8 and "Apache" in str(arc.get("license", "")) and len(arc.get("rows", [])) == arc.get("n_tasks", -1),
        f"n={arc.get('n_tasks')}, solved={arc.get('solved')}/{arc.get('n_tasks')}")
    rec("V23_phase3_benchmarks_not_merged",
        "merged_score" not in p3 and "combined_external_score" not in p3,
        "AMA-Bench Token F1 and ARC-AGI-2 exact match kept strictly separate")
    rw_raw_c = [bool(x) for x in rw.get("raw_neural_cain", [])]
    rw_raw_n = [bool(x) for x in rw.get("raw_baseline", [])]
    if len(rw_raw_c) >= 8 and len(rw_raw_n) == len(rw_raw_c):
        mc_rw = _exact_mcnemar(rw_raw_c, rw_raw_n)
        rec("V24_phase3_real_source_recomputed",
            sum(rw_raw_c) / len(rw_raw_c) >= 0.75 and mc_rw["p_value"] < 0.05,
            f"cain={sum(rw_raw_c)}/{len(rw_raw_c)}, baseline={sum(rw_raw_n)}/{len(rw_raw_n)}, p={mc_rw['p_value']}")
    else:
        rec("V24_phase3_real_source_recomputed", False, f"rows={len(rw_raw_c)}")

    # Phase 4 & 11: Capability discovery + Self-improvement ledger
    rec("V25_phase4_capability_discovery",
        len(p4_11.get("discovered_weaknesses", [])) >= 3 and p4_11.get("gates", {}).get("G08_autonomous_capability_discovery") is True,
        f"gaps={len(p4_11.get('discovered_weaknesses', []))}")
    rec("V26_phase11_self_improve_ledger",
        p4_11.get("candidates_evaluated", 0) >= 15
        and len(p4_11.get("unsafe_governance_blocks", [])) >= 4
        and len(p4_11.get("signed_promotions", [])) >= 4
        and p4_11.get("rollback_verified") is True
        and p4_11.get("governance_weakened") is False,
        f"total={p4_11.get('candidates_evaluated')}, unsafe_blocked={len(p4_11.get('unsafe_governance_blocks', []))}, rollback={p4_11.get('rollback_verified')}")

    # Phase 5: Neural + causal world model recomputation
    raw5 = p5.get("raw", {})
    c5_full = raw5.get("5_full_cain_integrated_reasoning", [])
    c5_pat = raw5.get("1_neural_pattern_matching", [])
    c5_nomem = raw5.get("2_neural_no_persistent_memory", [])
    if len(c5_full) == 20 and len(c5_pat) == 20 and len(c5_nomem) == 20:
        mc5_pat = _exact_mcnemar(c5_full, c5_pat)
        mc5_nm = _exact_mcnemar(c5_full, c5_nomem)
        rec("V27_phase5_neural_causal_recomputed",
            mc5_pat["gain"] >= 0.35 and mc5_pat["p_value"] < 0.01 and mc5_nm["gain"] >= 0.30 and mc5_nm["p_value"] < 0.01,
            f"vs_pat={mc5_pat}, vs_nomem={mc5_nm}")
    else:
        rec("V27_phase5_neural_causal_recomputed", False, f"len={len(c5_full)}")

    # Phase 6: 10-role autonomous scientific research (3 cycles + governance override blocked)
    rec("V28_phase6_10roles_3cycles",
        len(p6.get("roles", [])) == 10
        and p6.get("cycles_completed") == 3
        and bool(p6.get("director_override_of_governance_blocked", [False])[0])
        and p6.get("g09_passed") is True,
        f"roles={len(p6.get('roles', []))}, cycles={p6.get('cycles_completed')}")

    # Phases 7–10: Verticals, Transfer, Continual (0 weight updates), Collective
    tr = p7_10.get("transfer_8_pathways", {})
    cont = p7_10.get("continual_neural_learning", {})
    coll = p7_10.get("collective_neural", {})
    rec("V29_phase7_five_verticals", p7_10.get("gates", {}).get("G11_five_verticals") is True, "5 verticals verified")
    rec("V30_phase8_five_positive_three_negative_transfer",
        tr.get("positive_supported", 0) >= 5 and tr.get("negative_transfer_rejected", 0) >= 3,
        f"pos={tr.get('positive_supported')}, neg_rej={tr.get('negative_transfer_rejected')}")
    rec("V31_phase9_continual_zero_weight_updates",
        cont.get("mechanisms_changed", {}).get("model_weights_updated") is False
        and cont.get("poison_attempts_accepted") == 0
        and cont.get("g14_passed") is True,
        f"model_weights_updated={cont.get('mechanisms_changed', {}).get('model_weights_updated')}, forgetting={cont.get('forgetting_delta')}")
    rec("V32_phase10_collective_7arms_honest_control",
        len(coll.get("arms", {})) == 7
        and len(coll.get("models_participating", [])) >= 3
        and coll.get("g15_passed") is True,
        f"arms={len(coll.get('arms', {}))}, models={len(coll.get('models_participating', []))}")

    # Phase 12: Governed neural separate-process TCP execution + kill-switch
    rec("V33_phase12_governed_neural_tcp_enforcement",
        p12.get("passed") is True
        and p12.get("scenarios_passed") == p12.get("scenarios_total")
        and p12.get("effects_after_kill") == 0
        and p12.get("ledger_chain_verified") is True,
        f"scenarios={p12.get('scenarios_passed')}/{p12.get('scenarios_total')}, after_kill={p12.get('effects_after_kill')}")

    # Phase 13: Strict G17 wall-clock honesty
    g17_status = gates.get("G17", {}).get("status")
    g17_honest = (g17_status != "PASS") or (
        p13.get("status_file_state") == "COMPLETED"
        and float(p13.get("elapsed_wall_s", 0)) >= 43200.0
        and p13.get("duplicate_sequences") == 0
    )
    rec("V34_phase13_g17_wallclock_honesty",
        g17_honest and p13.get("present") is True and p13.get("hash_chain_verified") is True and p13.get("duplicate_sequences") == 0,
        f"G17={g17_status}, records={p13.get('journal_records')}, neural_cycles={p13.get('neural_proposal_cycles')}, dups={p13.get('duplicate_sequences')}")

    # Phase 14: Strict G18 external human review honesty
    g18_status = gates.get("G18", {}).get("status")
    signed_slots = sum(1 for s in p14.get("org_slots", []) if s.get("signed_today"))
    g18_honest = (g18_status != "PASS") or (p14.get("quorum_met_today") is True and signed_slots >= 2)
    rec("V35_phase14_g18_multi_org_honesty",
        g18_honest and p14.get("quorum_required") == 2 and signed_slots == 1 and p14.get("quorum_met_today") is False,
        f"G18={g18_status}, signed_slots={signed_slots}/3, quorum_met={p14.get('quorum_met_today')}")

    # Phase 15: Commercial truthfulness (10 docs, 0 outreach, 0 Stripe changes, 0 fabricated revenue)
    rec("V36_phase15_commercial_truthful",
        p15.get("deliverables_count") == 10
        and p15.get("outreach_sent") is False
        and p15.get("stripe_modified") is False
        and p15.get("revenue_fabricated") is False,
        f"deliverables={p15.get('deliverables_count')}, outreach=False, stripe_modified=False")

    # Overall status consistency
    gate_counts = results.get("gate_counts", {})
    re_pass = sum(1 for g in gates.values() if g["status"] == "PASS")
    re_part = sum(1 for g in gates.values() if g["status"] == "PARTIAL")
    re_fail = sum(1 for g in gates.values() if g["status"] == "FAIL")
    rec("V37_scorecard_counts_match",
        gate_counts.get("PASS") == re_pass and gate_counts.get("PARTIAL") == re_part and gate_counts.get("FAIL") == re_fail,
        f"PASS={re_pass}, PARTIAL={re_part}, FAIL={re_fail}")

    all_ok = all(c["ok"] for c in checks)
    return all_ok, checks


def main() -> int:
    if len(sys.argv) < 2:
        print("Usage: python3 -I verify_e122_offline.py <bundle_dir>", file=sys.stderr)
        return 2
    bundle_dir = pathlib.Path(sys.argv[1]).resolve()
    ok, checks = verify_bundle(bundle_dir)
    passed = sum(1 for c in checks if c["ok"])
    total = len(checks)
    print(json.dumps({"passed": ok, "checks_passed": passed, "checks_total": total, "checks": checks}, indent=1))
    print(f"E122 OFFLINE VERIFICATION: {passed}/{total} checks passed")
    return 0 if ok else 1


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