#!/usr/bin/env python3
"""E358-S 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"
SITES = ("cainstudio", "mcpgate", "clawx", "huggingface")
E356_SEAL = "OMEGA-000000370"
E357_SEAL = "OMEGA-000000373"
EX = {"E358S_MANIFEST.json", "E358S_SIGNED_BODY.json", "E358S_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E358S_OMEGA_SEAL.json",
      "E358S_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 _all(samples, key):
    return bool(samples) and all(
        all(s["sites"][i]["checks"][key]["ok"] for i in range(len(s["sites"])))
        for s in samples)


def decide(samples):
    H = {
        "H1_identity": "SUPPORTED" if _all(samples, "identity") else "NOT_SUPPORTED",
        "H2_status": "SUPPORTED" if _all(samples, "status_line") else "NOT_SUPPORTED",
        "H3_e356": ("SUPPORTED" if _all(samples, "e356_page") and _all(samples, "e356_snapshot")
                    else "NOT_SUPPORTED"),
        "H4_e357": ("SUPPORTED" if _all(samples, "e357_page") and _all(samples, "e357_snapshot")
                    else "NOT_SUPPORTED"),
        "H5_top": "SUPPORTED" if _all(samples, "e357_top") else "NOT_SUPPORTED",
        "H6_all_samples": ("SUPPORTED" if samples and all(s["attested"] for s in samples)
                           else "NOT_SUPPORTED"),
        "H7_external_review": "BLOCKED",
    }
    verdict = ("SURFACES_CONVERGED"
               if all(H[k] == "SUPPORTED" for k in H if k != "H7_external_review")
               else "NOT_CONVERGED")
    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 / "E358S_MANIFEST.json").read_text())
    pre = json.loads((d / "E358S_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E358S_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E358S_RUN_REPORT.json").read_text())
    acc = json.loads((d / "E358S_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E358S_DEVIATIONS.json").read_text())
    ext = json.loads((d / "E358S_EXTERNAL_REVIEW_STATUS.json").read_text())
    report_md = (d / "E358S_FINAL_REPORT.md").read_text()

    ck("manifest schema", man.get("schema") == "cain42.e358s.manifest.v1")
    ck("evolution", man.get("evolution") == "E358-S" and rep.get("evolution") == "E358-S")
    ck("status", man.get("status") == S and rep.get("status") == S)
    ck("designation", pre.get("evolution") == "E358-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 / "E358S_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 / "E358S_PREREGISTRATION.json").read_bytes())
       == frz["preregistration_sha256"] == rep["preregistration_sha256"])
    ck("freeze precedes run", frz["frozen_at"] <= rep["generated_at"])
    ck("source withheld", not any(p.name in ("run.py", "verify.py") for p in d.rglob("*")
                                  if p.is_file()))
    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_e358s_offline.py"))

    samples = rep["samples"]
    ck("samples", len(samples) == 3 and rep.get("sample_count") == 3)
    ck("sites", all(len(s["sites"]) == 4 for s in samples)
       and all(tuple(x["site"] for x in s["sites"]) == SITES for s in samples))
    ck("check schema", all(all(k in x["checks"] for k in
        ("home_200", "identity", "status_line", "e356_page", "e357_page",
         "e356_snapshot", "e357_snapshot", "e357_top", "e356_block"))
        for s in samples for x in s["sites"]))
    ck("snapshot fields", all(
        (not x["checks"]["e356_snapshot"]["ok"]
         or (x["checks"]["e356_snapshot"].get("seal") == E356_SEAL
             and x["checks"]["e356_snapshot"].get("name_rule_outcome") == "superorganism (candidate)"))
        and
        (not x["checks"]["e357_snapshot"]["ok"]
         or (x["checks"]["e357_snapshot"].get("seal") == E357_SEAL
             and x["checks"]["e357_snapshot"].get("verdict") == "DOCKET_VERIFIED"
             and x["checks"]["e357_snapshot"].get("scope_present") is True))
        for s in samples for x in s["sites"]))
    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_converged"]
       == sum(1 for s in samples if s["attested"]))
    ck("site counts", all(rep["finding"]["sites"][n] ==
                          sum(1 for s in samples for x in s["sites"] if x["site"] == n and x["attested"])
                          for n in SITES))
    ck("report verdict", f"**Preregistered verdict: {rep['verdict']}.**" in report_md)
    ck("acceptance", acc["verdict"] == rep["verdict"]
       and acc["all_pass"] == (rep["verdict"] == "SURFACES_CONVERGED"))
    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"]) >= 5)

    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())
