#!/usr/bin/env python3
"""E351 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"
EX = {"E351_MANIFEST.json", "E351_SIGNED_BODY.json", "E351_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E351_OMEGA_SEAL.json",
      "E351_TAMPER_RESULTS.json"}
CHECKS = ("cluster_mr01", "cluster_mr03", "governance", "continuous", "proof")


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 _all(samples, key):
    return bool(samples) and all(s.get("checks", {}).get(key, {}).get("ok") is True for s in samples)


def decide(samples):
    H = {
        "H1_cluster_mr01": "SUPPORTED" if _all(samples, "cluster_mr01") else "NOT_SUPPORTED",
        "H2_cluster_mr03": "SUPPORTED" if _all(samples, "cluster_mr03") else "NOT_SUPPORTED",
        "H3_governance": "SUPPORTED" if _all(samples, "governance") else "NOT_SUPPORTED",
        "H4_continuous": "SUPPORTED" if _all(samples, "continuous") else "NOT_SUPPORTED",
        "H5_proof": "SUPPORTED" if _all(samples, "proof") else "NOT_SUPPORTED",
        "H6_all_samples": ("SUPPORTED" if samples and all(s.get("attested") is True for s in samples)
                           else "NOT_SUPPORTED"),
        "H7_external_review": "BLOCKED",
    }
    verdict = ("LIVE_ASSURANCE_ATTESTED"
               if all(H[k] == "SUPPORTED" for k in H if k != "H7_external_review")
               else "NOT_ATTESTED")
    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 / "E351_MANIFEST.json").read_text())
    pre = json.loads((d / "E351_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E351_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E351_RUN_REPORT.json").read_text())
    acc = json.loads((d / "E351_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E351_DEVIATIONS.json").read_text())
    ext = json.loads((d / "E351_EXTERNAL_REVIEW_STATUS.json").read_text())
    report_md = (d / "E351_FINAL_REPORT.md").read_text()

    ck("manifest schema", man.get("schema") == "cain42.e351.manifest.v1")
    ck("evolution", man.get("evolution") == "E351" and rep.get("evolution") == "E351")
    ck("status", man.get("status") == S and rep.get("status") == S)
    ck("designation", pre.get("evolution") == "E351")
    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 / "E351_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 / "E351_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", "verify.py", "build_seq.py", "learner.py", "world.py", "grammar.py",
             "certificate.py", "oracles.py", "blizzard_public_e2e.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_e351_offline.py"))

    samples = rep["samples"]
    ck("samples", len(samples) == 3 and rep.get("sample_count") == 3)
    ck("sample schema", all(set(s) >= {"at", "checks", "attested"} for s in samples))
    ck("checks complete", all(all(k in s["checks"] for k in CHECKS) for s in samples))
    H, verdict = decide(samples)
    ck("verdict", verdict == rep["verdict"])
    ck("hypotheses", all(H[k] == rep["hypotheses"][k]["verdict"]
                         for k in H if k != "H7_external_review"))
    ck("attested count", rep["finding"]["samples_attested"]
       == sum(1 for s in samples if s["attested"]))
    ck("per-check counts", all(rep["finding"][k + "_ok"] == sum(1 for s in samples if s["checks"][k]["ok"])
                               for k in CHECKS))
    ck("freshness bound", all(
        (s["checks"]["continuous"].get("age_s") is not None
         and s["checks"]["continuous"]["age_s"] <= 3600
         and s["checks"]["proof"].get("age_s") is not None
         and s["checks"]["proof"]["age_s"] <= 3600)
        for s in samples))
    ck("report verdict", f"**Preregistered verdict: {rep['verdict']}.**" in report_md)
    ck("acceptance", acc["verdict"] == rep["verdict"]
       and acc["all_pass"] == (rep["verdict"] == "LIVE_ASSURANCE_ATTESTED"))
    ck("external", ext["status"] == "NOT_OBTAINED")
    ck("deviations recorded", [x.get("id") for x in dev.get("deviations", [])] == ["D1_post_run_hypothesis_fields"])
    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) == len(samples))
    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())
