#!/usr/bin/env python3
"""Standalone E188 record verifier: claim ledger, overclaim guard, browser-verifier results.

Imports no CAIN code. It verifies the signed E188 engineering record. It does NOT re-execute the E184 engine
(that source is withheld under the IP rule; the E184 public verifier is record-level).
"""
from __future__ import annotations
import hashlib
import json
import sys
from pathlib import Path

STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
EXTRAS = {"E188_SIGNED_BODY.json", "E188_VERIFICATION_RESULTS.json", "PUBLICATION.json", "E188_OMEGA_SEAL.json", "E188_TAMPER_RESULTS.json"}


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":")).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 main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    checks = []

    def ck(name, ok, detail=""):
        checks.append({"check": name, "ok": bool(ok), "detail": str(detail)[:300]})

    man = json.loads((B / "E188_MANIFEST.json").read_text())
    ck("status line", man.get("status") == STATUS)
    ck("engineering-verification label", man.get("label") == "ENGINEERING_VERIFICATION")
    body = {k: v for k, v in man.items() if k != "signature"}
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), canon(body))
        ck("signature", True)
    except Exception as ex:  # noqa: BLE001
        ck("signature", False, ex)
    files = man.get("files", {})
    ck("files exist", all((B / k).exists() for k in files))
    bad = [k for k, h in files.items() if (B / k).exists() and sha((B / k).read_bytes()) != h]
    ck("hashes", not bad, bad[:3])
    ck("merkle", merkle(sorted(B / k for k in files if (B / k).exists())) == man.get("merkle_root"))
    present = {str(x.relative_to(B)) for x in B.rglob("*") if x.is_file() and "__pycache__" not in x.parts and x.suffix != ".pyc"}
    unlisted = sorted(present - set(files) - EXTRAS - {"E188_MANIFEST.json"})
    ck("no unlisted file", not unlisted, unlisted[:5])
    sig_body = B / "E188_SIGNED_BODY.json"
    if sig_body.exists():
        ck("signed body matches", sig_body.read_bytes() == canon(body))

    claims = json.loads((B / "RSI_CLAIMS.json").read_text())
    ck("claim ledger", len(claims.get("claims", [])) >= 7 and len(claims.get("forbidden", [])) >= 5,
       f"{len(claims.get('claims', []))} claims, {len(claims.get('forbidden', []))} forbidden")
    ids = {c.get("id") for c in claims.get("claims", [])}
    ck("required claims present", {"C184-ENDPOINT", "C185-STRICT", "C183-EXPLORATORY", "C-SEALS", "C-VERIFY", "C179", "C-STATUS"} <= ids)
    guard = json.loads((B / "E188_CLAIM_GUARD.json").read_text())
    ck("guard all passed", guard.get("all_passed") is True)
    ck("guard surfaces", guard.get("surfaces_checked", 0) >= 20, guard.get("surfaces_checked"))
    ck("guard no forbidden hits", guard.get("forbidden_hits") == [], guard.get("forbidden_hits"))
    ck("guard checks all ok", all(c.get("ok") for c in guard.get("checks", [])))
    browser = json.loads((B / "E188_BROWSER_VERIFIER_RESULTS.json").read_text())
    ck("browser all ok", browser.get("all_ok") is True)
    for k in ("signature_ok", "file_hashes_ok", "per_step_ok", "pooled_ok", "holm_ok", "strict_ok", "claims_ok"):
        ck("browser " + k, browser.get(k) is True)
    ck("strict curve", browser.get("strict_curve") == [6, 14, 28, 33, 34], browser.get("strict_curve"))
    ck("WebCrypto runtime", str(browser.get("runtime", "")).startswith("node"), browser.get("runtime"))
    ck("E184/E185 evidence referenced", any("e184" in (c.get("evidence") or "") for c in claims.get("claims", []))
       and any("e185" in (c.get("evidence") or "") for c in claims.get("claims", [])))
    ck("no AGI claim", man.get("status") == STATUS)
    pub = B / "PUBLICATION.json"
    if pub.exists():
        pj = json.loads(pub.read_text())
        ck("publication merkle", pj.get("merkle_root") == man.get("merkle_root"))
        ck("four surfaces", len(pj.get("surfaces", {})) == 4, len(pj.get("surfaces", {})))
    else:
        ck("pre-publication", True)
    ok = all(x["ok"] for x in checks)
    print(json.dumps({"checks": len(checks), "passed": sum(x["ok"] for x in checks), "ok": ok,
                      "verification": "E188 engineering record; record-level; no engine re-execution"}))
    for x in checks:
        if not x["ok"]:
            print("FAIL", x["check"], x["detail"])
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main())
