#!/usr/bin/env python3
"""E348 standalone offline verifier (stdlib + cryptography; imports no CAIN code).

Recomputes every summary, hypothesis and the verdict from the 24 raw instances and checks the
manifest/signature/Merkle root, the preregistration freeze, the salt commitments, the row chain, the
deviations and the source-withholding rule. Record-level: no re-execution.
"""
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 = {"E348_MANIFEST.json", "E348_SIGNED_BODY.json", "E348_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E348_OMEGA_SEAL.json",
      "E348_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]),
            "min_margin_one": sum(1 for r in sub if r["min_margin"] == 1),
            "mean_ceiling": mean([r["ceiling"] for r in sub]),
            "mean_aug2_extra": mean([r["aug2_extra"] for r in sub]),
            "mean_aug4_extra": mean([r["aug4_extra"] for r in sub]),
            "mean_aug8_extra": mean([r["aug8_extra"] for r in sub]),
            "mean_augceil_extra": mean([r["augceil_extra"] for r in sub]),
            "ceiling_reached": sum(1 for r in sub if r["augceil_ok"]),
            "rand2_margin_one": sum(1 for r in sub if r["rand2_margin"] == 1),
            "mean_det_min_5pct": mean([r["det_min"]["5pct"] for r in sub]),
            "mean_det_ceil_5pct": mean([r["det_ceil"]["5pct"] for r in sub]),
        }
    out["all"] = {
        "instances": len(rows),
        "mean_min_rows": mean([r["min_rows"] for r in rows]),
        "min_margin_one": sum(1 for r in rows if r["min_margin"] == 1),
        "mean_ceiling": mean([r["ceiling"] for r in rows]),
        "min_ceiling": min(r["ceiling"] for r in rows),
        "max_ceiling": max(r["ceiling"] for r in rows),
        "mean_aug2_extra": mean([r["aug2_extra"] for r in rows]),
        "max_aug2_extra": max(r["aug2_extra"] for r in rows),
        "mean_aug4_extra": mean([r["aug4_extra"] for r in rows]),
        "max_aug4_extra": max(r["aug4_extra"] for r in rows),
        "mean_aug8_extra": mean([r["aug8_extra"] for r in rows]),
        "mean_augceil_extra": mean([r["augceil_extra"] for r in rows]),
        "ceiling_reached": sum(1 for r in rows if r["augceil_ok"]),
        "rand2_margin_one": sum(1 for r in rows if r["rand2_margin"] == 1),
        "mean_det_min_5pct": mean([r["det_min"]["5pct"] for r in rows]),
        "mean_det_ceil_5pct": mean([r["det_ceil"]["5pct"] for r in rows]),
        "max_det_ceil_5pct": max(r["det_ceil"]["5pct"] for r in rows),
        "mean_det_min_1pct": mean([r["det_min"]["1pct"] for r in rows]),
        "mean_det_ceil_1pct": mean([r["det_ceil"]["1pct"] for r in rows]),
        "mean_det_min_10pct": mean([r["det_min"]["10pct"] for r in rows]),
        "mean_det_ceil_10pct": mean([r["det_ceil"]["10pct"] for r in rows]),
        "mean_augment_seconds": mean([r["seconds"]["augment"] for r in rows]),
    }
    return out


def decide(rows, sums):
    a = sums["all"]

    def sub(salt):
        aa = summarize([r for r in rows if r["salt"] == salt])["all"]
        return {"min_margin_one": aa["min_margin_one"], "aug2": aa["max_aug2_extra"],
                "aug4": aa["max_aug4_extra"], "ceiling": aa["max_ceiling"],
                "max_det": aa["max_det_ceil_5pct"], "rand2": aa["rand2_margin_one"],
                "reach": aa["ceiling_reached"]}

    rp = sub("replication")
    H = {
        "H1_minimum_is_fragile": {
            "verdict": "SUPPORTED" if a["min_margin_one"] >= 20 else "NOT_SUPPORTED",
            "detail": "the minimum certificate has smallest margin 1 in >=20/24 instances (detection of the hardest decoy equals eps)"},
        "H2_margin_two_is_cheap": {
            "verdict": "SUPPORTED" if (a["max_aug2_extra"] <= 12
                                       and all(r["aug2_ok"] for r in rows)) else "NOT_SUPPORTED",
            "detail": "raising the smallest margin to 2 succeeds and costs <=12 extra rows in every instance"},
        "H3_margin_four_is_moderate": {
            "verdict": "SUPPORTED" if (a["max_aug4_extra"] <= 30 and all(r["aug4_ok"] for r in rows)) else "NOT_SUPPORTED",
            "detail": "raising the smallest margin to 4 succeeds and costs <=30 extra rows in every instance"},
        "H4_class_ceiling_caps_detection": {
            "verdict": "SUPPORTED" if (a["max_ceiling"] < 45 and a["max_det_ceil_5pct"] < 0.90) else "NOT_SUPPORTED",
            "detail": "the class ceiling is <45 in every instance, so no certificate can reach 90% hardest-decoy detection at 5% row noise"},
        "H5_structure_beats_random": {
            "verdict": "SUPPORTED" if a["rand2_margin_one"] >= 20 else "NOT_SUPPORTED",
            "detail": "adding the same number of random rows leaves the smallest margin at 1 in >=20/24 instances"},
        "H6_replication": {
            "verdict": "SUPPORTED" if (rp["min_margin_one"] >= 10 and rp["aug2"] <= 12 and rp["aug4"] <= 30
                                       and rp["ceiling"] < 45 and rp["max_det"] < 0.90
                                       and rp["rand2"] >= 10) 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 = ("ROBUSTNESS_CEILING_LAW_SUPPORTED"
               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 / "E348_MANIFEST.json").read_text())
    pre = json.loads((d / "E348_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E348_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E348_RUN_REPORT.json").read_text())
    salt = json.loads((d / "E348_SALT_REVEALED.json").read_text())
    acc = json.loads((d / "E348_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E348_DEVIATIONS.json").read_text())
    ext = json.loads((d / "E348_EXTERNAL_REVIEW_STATUS.json").read_text())
    report_md = (d / "E348_FINAL_REPORT.md").read_text()
    public_md = (d / "E348_PUBLIC_SUMMARY.md").read_text()

    ck("manifest schema", man.get("schema") == "cain42.e348.manifest.v1")
    ck("evolution", man.get("evolution") == "E348" and rep.get("evolution") == "E348")
    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 / "E348_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 / "E348_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_e348_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("margins consistent", all(r["min_margin"] <= r["ceiling"] for r in rows))
    ck("augmentation reaches its targets", all(r["aug2_ok"] and r["aug4_ok"] and r["aug8_ok"]
                                               for r in rows))
    ck("min certificate sound", all(r["min_margin"] >= 1 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,
        "min_margin_one": a["min_margin_one"], "mean_min_rows": a["mean_min_rows"],
        "mean_ceiling": a["mean_ceiling"], "min_ceiling": a["min_ceiling"],
        "max_ceiling": a["max_ceiling"],
        "mean_aug2_extra": a["mean_aug2_extra"], "max_aug2_extra": a["max_aug2_extra"],
        "mean_aug4_extra": a["mean_aug4_extra"], "max_aug4_extra": a["max_aug4_extra"],
        "mean_aug8_extra": a["mean_aug8_extra"],
        "mean_augceil_extra": a["mean_augceil_extra"], "ceiling_reached": a["ceiling_reached"],
        "rand2_margin_one": a["rand2_margin_one"],
        "mean_det_min_1pct": a["mean_det_min_1pct"], "mean_det_ceil_1pct": a["mean_det_ceil_1pct"],
        "mean_det_min_5pct": a["mean_det_min_5pct"], "mean_det_ceil_5pct": a["mean_det_ceil_5pct"],
        "max_det_ceil_5pct": a["max_det_ceil_5pct"],
        "mean_det_min_10pct": a["mean_det_min_10pct"], "mean_det_ceil_10pct": a["mean_det_ceil_10pct"],
        "t2_k2_mean_ceiling": c["T2_K2"]["mean_ceiling"],
        "t3_k3_mean_ceiling": c["T3_K3"]["mean_ceiling"],
        "mean_augment_seconds": a["mean_augment_seconds"],
    }
    ck("finding", all(f[k] == v for k, v in expected.items()))
    hl = man.get("headline") or {}
    for k in ("instances", "min_margin_one", "mean_min_rows", "mean_ceiling", "max_ceiling",
              "mean_aug2_extra", "max_aug2_extra", "mean_aug4_extra", "max_aug4_extra",
              "mean_augceil_extra", "ceiling_reached", "rand2_margin_one",
              "mean_det_min_5pct", "mean_det_ceil_5pct", "max_det_ceil_5pct"):
        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"] == "ROBUSTNESS_CEILING_LAW_SUPPORTED"))
    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())
