#!/usr/bin/env python3
"""E354-B standalone offline verifier (stdlib + cryptography only; imports no CAIN code)."""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
EX = {"E354B_MANIFEST.json", "E354B_SIGNED_BODY.json", "E354B_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E354B_OMEGA_SEAL.json",
      "E354B_TAMPER_RESULTS.json"}


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def sha(b):
    return hashlib.sha256(b).hexdigest()


def merkle(paths):
    leaves = sorted(sha(p.read_bytes()) for p in paths)
    if not leaves:
        return sha(b"")
    while len(leaves) > 1:
        if len(leaves) % 2:
            leaves.append(leaves[-1])
        leaves = [sha((leaves[i] + leaves[i + 1]).encode()) for i in range(0, len(leaves), 2)]
    return leaves[0]


def chain_ok(ch):
    prev = "0" * 64
    for i, x in enumerate(ch):
        if x.get("i") != i or x.get("prev") != prev:
            return False
        prev = x["hash"]
    return True


def decide(stages):
    h1 = stages["H1_monotonic"]
    h2 = stages["H2_refusal"]
    h3 = stages["H3_partition"]
    h4 = stages["H4_fuzz"]
    h5 = stages["H5_live_clusters"]
    h6 = stages["H6_soak_ckpt0"]

    h1_ok = (len(h1["disk_cases"]) == 10 and all(c["ok"] is True for c in h1["disk_cases"])
             and len(h1["stepdown_cases"]) == 5 and all(c["ok"] is True and c["voted_low"] is False for c in h1["stepdown_cases"]))
    h2_ok = len(h2["cases"]) == 8 and all(c["ok"] is True for c in h2["cases"])
    h3_ok = len(h3["cases"]) == 3 and all(c["ok"] is True for c in h3["cases"])
    h4_ok = (set(h4["positions"]) == {"n1", "n2", "n3", "n4"}
             and all(v["ok"] is True and v["findings"] == 0 and v["safe"] is True and v["post_fuzz"] == "ALLOW"
                     for v in h4["positions"].values()))
    h5_ok = (len(h5["samples"]) == 2
             and all(s["ok"] is True and s["cain_mr_03"]["verdict"] == "SAFE" and s["cain_mr_01"]["verdict"] == "SAFE"
                     and s["cain_mr_03"]["reachable"] == 4 and s["cain_mr_01"]["reachable"] == 4
                     and not s["cain_mr_03"]["quarantined"] and not s["cain_mr_01"]["quarantined"]
                     and not s["cain_mr_03"]["findings"] and not s["cain_mr_01"]["findings"]
                     for s in h5["samples"]))
    h6_ok = h6.get("ok") is True and h6.get("verifier_returncode") == 0

    H = {
        "H1_monotonic_left_view": "SUPPORTED" if h1_ok else "NOT_SUPPORTED",
        "H2_left_view_vote_and_propose_refusal": "SUPPORTED" if h2_ok else "NOT_SUPPORTED",
        "H3_healed_partition_liveness": "SUPPORTED" if h3_ok else "NOT_SUPPORTED",
        "H4_byzantine_fuzz_zero_findings": "SUPPORTED" if h4_ok else "NOT_SUPPORTED",
        "H5_live_dual_cluster_safe": "SUPPORTED" if h5_ok else "NOT_SUPPORTED",
        "H6_fresh_48h_soak_checkpoint0_valid": "SUPPORTED" if h6_ok else "NOT_SUPPORTED",
        "H7_independent_witness_and_external_review": "BLOCKED",
    }
    verdict = ("PBFT_MONOTONIC_SAFETY_VERIFIED"
               if all(H[k] == "SUPPORTED" for k in H if k != "H7_independent_witness_and_external_review")
               else "NOT_SUPPORTED")
    return H, verdict


def main():
    d = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    checks = []

    def ck(name, cond):
        checks.append((name, bool(cond)))

    man = json.loads((d / "E354B_MANIFEST.json").read_text())
    pre = json.loads((d / "E354B_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E354B_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E354B_RUN_REPORT.json").read_text())
    acc = json.loads((d / "E354B_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E354B_DEVIATIONS.json").read_text())
    ext = json.loads((d / "E354B_EXTERNAL_REVIEW_STATUS.json").read_text())
    report_md = (d / "E354B_FINAL_REPORT.md").read_text()

    ck("manifest schema", man.get("schema") == "cain42.e354b.manifest.v1")
    ck("evolution", man.get("evolution") == "E354-B" and rep.get("evolution") == "E354-B")
    ck("status", man.get("status") == S and rep.get("status") == S)
    ck("designation", pre.get("evolution") == "E354-B")
    files = sorted(p for p in d.rglob("*") if p.is_file()
                   and str(p.relative_to(d)) not in EX and "__pycache__" not in p.parts)
    ck("manifest files", set(man["files"]) == {str(p.relative_to(d)) for p in files})
    ck("manifest hashes", all(sha(p.read_bytes()) == man["files"][str(p.relative_to(d))] for p in files))
    ck("merkle", man["merkle_root"] == merkle(files))
    ck("merkle file", (d / "MERKLE_ROOT.txt").read_text().strip() == man["merkle_root"])

    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    body = json.loads((d / "E354B_SIGNED_BODY.json").read_text())
    pub = Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
    pub.verify(bytes.fromhex(man["signature"]), canon(body))
    ck("signature", True)
    ck("signed body binds merkle", body["merkle_root"] == man["merkle_root"])

    ck("prereg freeze", sha((d / "E354B_PREREGISTRATION.json").read_bytes())
       == frz["preregistration_sha256"] == rep["preregistration_sha256"])
    ck("freeze precedes run", frz["frozen_at"] <= rep["generated_at"])

    leak = [p.name for p in d.rglob("*") if p.is_file() and p.name in
            ("run.py", "cain_pbft_engine_33.py", "message_fabric.py", "pbft_fuzz.py")]
    ck("source withheld", not leak)
    ck("no engine leak text", not any("from cain.cain2027" in p.read_text(errors="ignore")
                                      for p in d.rglob("*.py") if p.name != "verify_e354b_offline.py"))

    H, verdict = decide(rep["stages"])
    ck("verdict recomputed", verdict == rep["verdict"])
    ck("hypotheses recomputed", all(H[k] == rep["hypotheses"][k]["verdict"] for k in H))
    ck("h7 blocked", rep["hypotheses"]["H7_independent_witness_and_external_review"]["verdict"] == "BLOCKED")

    f = rep["finding"]
    st = rep["stages"]
    ck("disk count matches", f["disk_monotonic_passed"] == sum(c["ok"] for c in st["H1_monotonic"]["disk_cases"]))
    ck("stepdown count matches", f["stepdown_blocked_passed"] == sum(c["ok"] for c in st["H1_monotonic"]["stepdown_cases"]))
    ck("refusal count matches", f["refusal_passed"] == sum(c["ok"] for c in st["H2_refusal"]["cases"]))
    ck("partition count matches", f["partition_passed"] == sum(c["ok"] for c in st["H3_partition"]["cases"]))
    ck("fuzz findings match", f["fuzz_findings"] == sum(v["findings"] for v in st["H4_fuzz"]["positions"].values()))
    ck("live samples match", f["live_samples_ok"] == sum(s["ok"] for s in st["H5_live_clusters"]["samples"]))
    ck("soak ckpt0 match", f["soak_ckpt0_ok"] == st["H6_soak_ckpt0"]["ok"])

    ck("report verdict", f"**Preregistered verdict: {rep['verdict']}.**" in report_md)
    ck("acceptance", acc["verdict"] == rep["verdict"] and acc["all_pass"] == (rep["verdict"] == "PBFT_MONOTONIC_SAFETY_VERIFIED"))
    ck("external", ext["status"] == "NOT_OBTAINED" and ext.get("independent_witnesses") == 0)
    ck("deviations schema", isinstance(dev.get("deviations"), list))
    ck("model calls zero", rep["resources"]["model_calls"] == 0 and rep["resources"]["api_spend_usd"] == 0.0)
    ck("limits present", len(rep["limits"]) >= 6)

    ch = [json.loads(l) for l in (d / "checkpoints/claim_chain.jsonl").read_text().splitlines()]
    ck("row chain", chain_ok(ch) and len(ch) == 6)
    ck("row chain head", ch[-1]["hash"] == rep["checkpoint"]["head"])
    cp = json.loads((d / "checkpoints/claim_chain.json").read_text())
    ck("checkpoint", cp["count"] == len(ch) and cp["head"] == ch[-1]["hash"] and cp["mid"] == ch[len(ch) // 2]["hash"])

    bad = [n for n, ok in checks if not ok]
    for n, ok in checks:
        print(("PASS " if ok else "FAIL ") + n)
    print(f"{len(checks) - len(bad)}/{len(checks)} checks passed")
    return 0 if not bad else 1


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