#!/usr/bin/env python3
"""E346 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 and
the source-withholding rule. Record-level: the solver is not re-executed.
"""
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 = {"E346_MANIFEST.json", "E346_SIGNED_BODY.json", "E346_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E346_OMEGA_SEAL.json",
      "E346_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_greedy1": mean([r["greedy1"] for r in sub]),
            "mean_greedy5": mean([r["greedy5"] for r in sub]),
            "mean_exact": mean([r["exact"] for r in sub]),
            "mean_lp_ceil": mean([r["lp_ceil"] for r in sub]),
            "strict_improvements": sum(1 for r in sub if (r["greedy_gap"] or 0) > 0),
            "max_greedy_gap": max([r["greedy_gap"] for r in sub if r["greedy_gap"] is not None], default=None),
            "mean_greedy_gap": mean([r["greedy_gap"] for r in sub]),
            "mean_lp_gap": mean([r["lp_gap"] for r in sub]),
            "max_lp_gap": max([r["lp_gap"] for r in sub if r["lp_gap"] is not None], default=None),
            "proven": sum(1 for r in sub if r["exact_proven"]),
            "sound": sum(1 for r in sub if r["exact_sound"]),
            "mean_exact_seconds": mean([r["seconds"]["exact"] for r in sub]),
            "max_exact_seconds": max([r["seconds"]["exact"] for r in sub], default=None),
        }
    out["all"] = {
        "instances": len(rows),
        "mean_greedy1": mean([r["greedy1"] for r in rows]),
        "mean_greedy5": mean([r["greedy5"] for r in rows]),
        "mean_exact": mean([r["exact"] for r in rows]),
        "mean_lp_ceil": mean([r["lp_ceil"] for r in rows]),
        "greedy_gap_instances": sum(1 for r in rows if (r["greedy_gap"] or 0) > 0),
        "greedy1_gap_instances": sum(1 for r in rows if (r["greedy1_gap"] or 0) > 0),
        "max_greedy_gap": max([r["greedy_gap"] for r in rows if r["greedy_gap"] is not None], default=None),
        "mean_greedy_gap": mean([r["greedy_gap"] for r in rows]),
        "mean_lp_gap": mean([r["lp_gap"] for r in rows]),
        "max_lp_gap": max([r["lp_gap"] for r in rows if r["lp_gap"] is not None], default=None),
        "lp_valid": sum(1 for r in rows if r["lp_valid"] is True),
        "proven": sum(1 for r in rows if r["exact_proven"]),
        "sound": sum(1 for r in rows if r["exact_sound"]),
        "mean_exact_seconds": mean([r["seconds"]["exact"] for r in rows]),
        "max_exact_seconds": max([r["seconds"]["exact"] for r in rows], default=None),
    }
    return out


def decide(rows, sums):
    def rep(sub):
        return {
            "sound": all(r["exact_sound"] for r in sub),
            "never_worse": all((r["greedy_gap"] or 0) >= 0 for r in sub),
            "proven": sum(1 for r in sub if r["exact_proven"]),
            "lp_valid": all(r["lp_valid"] is True for r in sub),
            "lp_mean": mean([r["lp_gap"] for r in sub]),
            "lp_max": max([r["lp_gap"] for r in sub if r["lp_gap"] is not None], default=None),
        }

    a = rep(rows)
    rp = rep([r for r in rows if r["salt"] == "replication"])
    H = {
        "H1_exact_sound": {"verdict": "SUPPORTED" if a["sound"] else "NOT_SUPPORTED",
                           "detail": "every exact certificate covers every wrong rule of the declared class"},
        "H2_exact_never_worse": {"verdict": "SUPPORTED" if a["never_worse"] else "NOT_SUPPORTED",
                                 "detail": "the exact optimum is no larger than the best-of-5 greedy certificate in every instance"},
        "H3_optimality_proven": {"verdict": "SUPPORTED" if a["proven"] >= 22 else "NOT_SUPPORTED",
                                 "detail": "optimality is proven by covering-separation termination inside the 75 s box in >=22/24 instances"},
        "H4_lp_lower_bound": {"verdict": "SUPPORTED" if (a["lp_valid"] and (a["lp_mean"] or 0) <= 1.5
                                                        and (a["lp_max"] or 0) <= 3) else "NOT_SUPPORTED",
                              "detail": "ceil(LP) <= exact in every instance, mean integrality gap <=1.5 rows and max <=3"},
        "H5_replication": {"verdict": "SUPPORTED" if (rp["sound"] and rp["never_worse"] and rp["proven"] >= 11
                                                     and rp["lp_valid"] and (rp["lp_mean"] or 0) <= 1.5
                                                     and (rp["lp_max"] or 0) <= 3) else "NOT_SUPPORTED",
                           "detail": "H1, H2, H3 and H4 hold on the replication salt"},
        "H6_external_review": {"verdict": "BLOCKED", "detail": "external review NOT OBTAINED"},
    }
    gated = [k for k in H if k != "H6_external_review"]
    verdict = ("EXACT_MINIMUM_CLASS_CERTIFICATE_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 / "E346_MANIFEST.json").read_text())
    pre = json.loads((d / "E346_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E346_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E346_RUN_REPORT.json").read_text())
    salt = json.loads((d / "E346_SALT_REVEALED.json").read_text())
    acc = json.loads((d / "E346_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E346_DEVIATIONS.json").read_text())
    ext = json.loads((d / "E346_EXTERNAL_REVIEW_STATUS.json").read_text())
    report_md = (d / "E346_FINAL_REPORT.md").read_text()
    public_md = (d / "E346_PUBLIC_SUMMARY.md").read_text()

    ck("manifest schema", man.get("schema") == "cain42.e346.manifest.v1")
    ck("evolution", man.get("evolution") == "E346" and rep.get("evolution") == "E346")
    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 / "E346_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 / "E346_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_e346_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("exact row count", all(r["exact"] is None or r["exact"] == len(r["exact_rows"]) for r in rows))
    ck("exact sound rows", all(r["exact_sound"] for r in rows))
    ck("greedy sound rows", all(r["greedy5_uncovered"] == 0 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,
        "exact_unsound": len(rows) - a["sound"],
        "exact_proven": a["proven"], "exact_proven_fraction": round(a["proven"] / len(rows), 6),
        "exact_mean_seconds": a["mean_exact_seconds"], "exact_max_seconds": a["max_exact_seconds"],
        "greedy_gap_instances": a["greedy_gap_instances"],
        "greedy_gap_rate": round(a["greedy_gap_instances"] / len(rows), 6),
        "max_greedy_gap": a["max_greedy_gap"], "mean_greedy_gap": a["mean_greedy_gap"],
        "greedy1_gap_instances": a["greedy1_gap_instances"],
        "mean_greedy1": a["mean_greedy1"], "mean_greedy5": a["mean_greedy5"],
        "mean_exact": a["mean_exact"], "mean_lp_ceil": a["mean_lp_ceil"],
        "lp_valid": a["lp_valid"], "mean_lp_gap": a["mean_lp_gap"], "max_lp_gap": a["max_lp_gap"],
        "t2_k2_mean_exact": c["T2_K2"]["mean_exact"],
        "t2_k2_mean_greedy5": c["T2_K2"]["mean_greedy5"],
        "t3_k3_mean_exact": c["T3_K3"]["mean_exact"],
        "t3_k3_mean_greedy5": c["T3_K3"]["mean_greedy5"],
        "t2_k2_strict": c["T2_K2"]["strict_improvements"],
        "t3_k3_strict": c["T3_K3"]["strict_improvements"],
        "mean_exact_seconds": a["mean_exact_seconds"],
        "max_exact_seconds": a["max_exact_seconds"],
    }
    ck("finding", all(f[k] == v for k, v in expected.items()))
    hl = man.get("headline") or {}
    for k in ("instances", "class_k2_rules", "class_k3_rules", "exact_unsound", "exact_proven",
              "greedy_gap_instances", "max_greedy_gap", "mean_greedy_gap", "greedy1_gap_instances",
              "mean_greedy5", "mean_exact", "mean_lp_gap", "max_lp_gap", "exact_mean_seconds",
              "exact_max_seconds"):
        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"] == "EXACT_MINIMUM_CLASS_CERTIFICATE_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())
