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

import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
CONDS = ("T2_K2", "T3_K3")
EX = {"E354_MANIFEST.json", "E354_SIGNED_BODY.json", "E354_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E354_OMEGA_SEAL.json",
      "E354_TAMPER_RESULTS.json"}
LEAK_NAMES = {"run.py", "verify.py", "build_seq.py", "learner.py", "world.py", "grammar.py",
              "certificate.py", "oracles.py", "certmin.py", "classspace.py", "covers.py"}


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 mean(xs):
    xs = [x for x in xs if x is not None]
    return round(sum(xs) / len(xs), 6) if xs else None


def summarize(rows):
    out = {"instances": len(rows), "conditions": {}}
    for cond in CONDS:
        sub = [r for r in rows if r["condition"] == cond]
        out["conditions"][cond] = {
            "instances": len(sub),
            "class_size": sub[0]["class_size"] if sub else None,
            "mean_min_rows": mean([r["min_rows"] for r in sub]),
            "mean_single_detection": mean([r["single_drift_detection"] for r in sub]),
            "mean_two_detection": mean([r["two_drift_detection"] for r in sub]),
            "mean_ratio_single": mean([r["ratio_single"] for r in sub]),
            "mean_l95_single": mean([r["l95_single"] for r in sub]),
        }
    out["all"] = {
        "instances": len(rows),
        "mean_min_rows": mean([r["min_rows"] for r in rows]),
        "in_class_complete": sum(1 for r in rows if r["in_class_detection"] == 1.0),
        "mean_single_detection": mean([r["single_drift_detection"] for r in rows]),
        "max_single_detection": max(r["single_drift_detection"] for r in rows),
        "mean_two_detection": mean([r["two_drift_detection"] for r in rows]),
        "max_two_detection": max(r["two_drift_detection"] for r in rows),
        "mean_l95_single": mean([r["l95_single"] for r in rows]),
        "min_l95_single": min(r["l95_single"] for r in rows),
        "mean_l95_two": mean([r["l95_two"] for r in rows]),
        "mean_ratio_single": mean([r["ratio_single"] for r in rows]),
        "min_ratio_single": min(r["ratio_single"] for r in rows),
        "max_ratio_single": max(r["ratio_single"] for r in rows),
        "mean_ratio_two": mean([r["ratio_two"] for r in rows]),
        "instances_below_10pct": sum(1 for r in rows if r["single_drift_detection"] < 0.10),
        "instances_ratio_ge20": sum(1 for r in rows if r["ratio_single"] >= 20.0),
    }
    return out


def decide(rows, sums):
    a = sums["all"]
    ra = summarize([r for r in rows if r["salt"] == "replication"])["all"]

    def ok(d):
        return (d["in_class_complete"] >= 10 and d["max_single_detection"] < 0.10
                and d["min_ratio_single"] >= 20.0)

    H = {
        "H1_in_class_still_complete": {
            "verdict": "SUPPORTED" if a["in_class_complete"] == 24 else "NOT_SUPPORTED",
            "detail": "the certificate still detects every in-class drift in all 24 instances"},
        "H2_single_row_drift_is_mostly_blind": {
            "verdict": "SUPPORTED" if a["max_single_detection"] < 0.10 else "NOT_SUPPORTED",
            "detail": "a one-row out-of-class drift is detected with probability m/256 < 0.10 in every instance"},
        "H3_two_row_drift_is_mostly_blind": {
            "verdict": "SUPPORTED" if a["max_two_detection"] < 0.15 else "NOT_SUPPORTED",
            "detail": "a two-row out-of-class drift is detected with probability < 0.15 in every instance"},
        "H4_95pct_needs_the_whole_cube": {
            "verdict": "SUPPORTED" if a["min_ratio_single"] >= 20.0 else "NOT_SUPPORTED",
            "detail": "95% detection of a one-row drift needs at least 20x the certificate's rows in every instance"},
        "H5_no_certificate_advantage": {
            "verdict": "SUPPORTED" if all(abs(r["single_drift_detection"] - r["min_rows"] / 256) < 1e-6
                                          for r in rows) else "NOT_SUPPORTED",
            "detail": "the certificate's one-row detection equals a random lease of the same size in every instance"},
        "H6_replication": {"verdict": "SUPPORTED" if ok(ra) else "NOT_SUPPORTED",
                           "detail": "H1-H5 hold on the replication salt"},
        "H7_external_review": {"verdict": "BLOCKED", "detail": "external review NOT OBTAINED"},
    }
    gated = [k for k in H if k != "H7_external_review"]
    verdict = ("MINIMAL_DRIFT_BLIND_SPOT_CONFIRMED"
               if all(H[k]["verdict"] == "SUPPORTED" for k in gated) else "NOT_SUPPORTED")
    return H, verdict


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


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 / "E354_MANIFEST.json").read_text())
    pre = json.loads((d / "E354_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E354_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E354_RUN_REPORT.json").read_text())
    salt = json.loads((d / "E354_SALT_REVEALED.json").read_text())
    acc = json.loads((d / "E354_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E354_DEVIATIONS.json").read_text())
    ext = json.loads((d / "E354_EXTERNAL_REVIEW_STATUS.json").read_text())
    report_md = (d / "E354_FINAL_REPORT.md").read_text()
    public_md = (d / "E354_PUBLIC_SUMMARY.md").read_text()

    ck("manifest schema", man.get("schema") == "cain42.e354.manifest.v1")
    ck("evolution", man.get("evolution") == "E354" and rep.get("evolution") == "E354")
    ck("status", man.get("status") == S and rep.get("status") == S)
    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 / "E354_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 / "E354_PREREGISTRATION.json").read_bytes())
       == frz["preregistration_sha256"] == rep["preregistration_sha256"])
    ck("freeze precedes run", frz["frozen_at"] <= rep["generated_at"])
    ck("salt commitments", all(sha(bytes.fromhex(v)) == pre["salt_commitment_sha256"][k]
                               for k, v in salt["salts"].items()))
    ck("salt revealed after run", salt["revealed_at"] >= rep["generated_at"])

    leak = [p.name for p in d.rglob("*") if p.is_file() and p.name in LEAK_NAMES]
    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_e354_offline.py"))

    prow, rrow = rep["sets"]["primary"]["rows"], rep["sets"]["replication"]["rows"]
    rows = prow + rrow
    ck("instances", len(rows) == 24 and len(prow) == 12 and len(rrow) == 12)
    ck("conditions complete", all(sum(1 for r in rows if r["condition"] == c) == 12 for c in CONDS))
    ck("class sizes", all(r["class_size"] == (6232 if r["k_declared"] == 2 else 219144)
                          for r in rows))
    ck("certificate margin", all(r["min_margin"] >= 1 and r["in_class_detection"] == 1.0 for r in rows))
    ck("detection bounds", all(0.0 <= r["single_drift_detection"] <= 1.0 for r in rows))
    ck("ratio consistent", all(abs(r["ratio_single"] - r["l95_single"] / r["min_rows"]) < 1e-6 for r in rows))

    sa = summarize(rows)
    ck("summary primary", summarize(prow) == rep["summaries"]["primary"])
    ck("summary replication", summarize(rrow) == rep["summaries"]["replication"])
    ck("summary all", sa == rep["summaries"]["all"])
    H, verdict = decide(rows, sa)
    ck("verdict", verdict == rep["verdict"])
    ck("hypotheses", all(H[k]["verdict"] == rep["hypotheses"][k]["verdict"] for k in H))
    ck("hypothesis details", all(H[k]["detail"] == rep["hypotheses"][k]["detail"] for k in H))

    f = rep["finding"]
    c = sa["conditions"]
    a = sa["all"]
    expected = {
        "instances": len(rows),
        "class_k2_rules": 6232, "class_k3_rules": 219144,
        "mean_min_rows": a["mean_min_rows"], "in_class_complete": a["in_class_complete"],
        "mean_single_detection": a["mean_single_detection"],
        "max_single_detection": a["max_single_detection"],
        "mean_two_detection": a["mean_two_detection"],
        "max_two_detection": a["max_two_detection"],
        "mean_l95_single": a["mean_l95_single"], "min_l95_single": a["min_l95_single"],
        "mean_l95_two": a["mean_l95_two"],
        "mean_ratio_single": a["mean_ratio_single"], "min_ratio_single": a["min_ratio_single"],
        "max_ratio_single": a["max_ratio_single"], "mean_ratio_two": a["mean_ratio_two"],
        "instances_below_10pct": a["instances_below_10pct"],
        "instances_ratio_ge20": a["instances_ratio_ge20"],
        "t2_k2_mean_single_detection": c["T2_K2"]["mean_single_detection"],
        "t3_k3_mean_single_detection": c["T3_K3"]["mean_single_detection"],
    }
    ck("finding", all(f[k] == v for k, v in expected.items()))
    hl = man.get("headline") or {}
    for k in ("instances", "mean_min_rows", "in_class_complete", "mean_single_detection",
              "max_single_detection", "mean_two_detection", "max_two_detection",
              "mean_l95_single", "min_l95_single", "mean_ratio_single", "min_ratio_single",
              "max_ratio_single", "mean_ratio_two", "instances_below_10pct",
              "instances_ratio_ge20"):
        ck(f"headline {k}", hl.get(k) == expected[k])

    ck("report verdict", f"**Preregistered verdict: {rep['verdict']}.**" in report_md)
    ck("public summary verdict", rep["verdict"] in public_md)
    ck("acceptance", acc["verdict"] == rep["verdict"]
       and acc["all_pass"] == (rep["verdict"] == "MINIMAL_DRIFT_BLIND_SPOT_CONFIRMED"))
    ck("external", ext["status"] == "NOT_OBTAINED")
    ck("deviations recorded", isinstance(dev.get("deviations"), list)
       and all(set(x) >= {"id", "text"} for x in dev["deviations"]))
    ck("model calls zero", rep["resources"]["model_calls"] == 0
       and rep["resources"]["api_spend_usd"] == 0.0)
    ck("limits present", len(rep["limits"]) >= 8)

    ch = [json.loads(l) for l in (d / "checkpoints/claim_chain.jsonl").read_text().splitlines()]
    ck("row chain", chain_ok(ch) and len(ch) == len(rows))
    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())
