#!/usr/bin/env python3
"""GMA standalone verifier — record-level. Verifies the signed certificate and bundle.

Checks: manifest signature, file hashes, Merkle root, certificate signature, scope-root recomputation,
row/count consistency, the seal snapshot binding, and that negatives are labelled. It does not
re-execute any study (the certificate was built by doing so).
"""
from __future__ import annotations
import hashlib, json, sys
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey


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(files):
    l = sorted(sha(p.read_bytes()) for p in files)
    while len(l) > 1:
        if len(l) % 2: l.append(l[-1])
        l = [sha((l[i] + l[i + 1]).encode()) for i in range(0, len(l), 2)]
    return l[0] if l else sha(b"")


def main():
    root = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
    ck, fail = [], []
    def check(n, ok, d=""):
        ck.append({"check": n, "ok": bool(ok), "detail": d})
        if not ok: fail.append(n)

    cert = json.loads((root / "GMA_CERTIFICATE.json").read_text())
    scope = json.loads((root / "GMA_SCOPE.json").read_text())
    snap = json.loads((root / "GMA_SEAL_SNAPSHOT.json").read_text())
    man = json.loads((root / "MANIFEST.json").read_text())

    body = {k: cert[k] for k in sorted(cert) if k != "signature"}
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(cert["signature"]), canon(body))
        check("certificate signature", True)
    except Exception:
        check("certificate signature", False)

    rows = cert["rows"]
    recomputed = sha(canon([[r["name"], r["merkle_root"], r["seal_number"]] for r in rows]))
    check("scope root recomputes from the rows", recomputed == cert["scope_root"], recomputed)
    check("scope file matches the certificate", scope["scope"] == cert["scope"] and scope["scope_root"] == cert["scope_root"])
    check("scope has one unique row per bundle",
          len(rows) == len(cert["scope"]) and sorted(r["name"] for r in rows) == sorted(cert["scope"]))
    check("every row is bound to the seal snapshot",
          all(r["name"] in snap["entries"]
              and snap["entries"][r["name"]]["seal_number"] == r["seal_number"]
              and snap["entries"][r["name"]]["merkle_root"] == r["merkle_root"]
              and snap["entries"][r["name"]]["verdict"] == r["seal_verdict"] for r in rows))
    check("every seal is ALLOWED", all(r["seal_verdict"] == "ALLOWED" for r in rows))
    check("every merkle matches its seal", all(r["merkle_matches_seal"] for r in rows))
    check("every auditor exited 0 from a clean copy", all(r["verifier_exit"] == 0 for r in rows))
    check("record_valid is implied by exit 0, seal and merkle",
          all(r["record_valid"] == (r["verifier_exit"] == 0 and r["seal_verdict"] == "ALLOWED"
                                    and r["merkle_matches_seal"]) for r in rows))
    check("all_valid is the conjunction", cert["all_valid"] == all(r["record_valid"] for r in rows))
    c = cert["counts"]
    check("counts agree with the rows",
          c["bundles"] == len(rows) and c["record_valid"] == sum(1 for r in rows if r["record_valid"])
          and c["negative"] == sum(1 for r in rows if r["negative"])
          and c["supported"] == sum(1 for r in rows if r["verdict"] and not r["negative"])
          and c["checks_passed"] == sum(r["checks_passed"] or 0 for r in rows)
          and c["checks_total"] == sum(r["checks_total"] or 0 for r in rows))
    check("negatives are labelled and kept",
          all((r["negative"] == (r["verdict"] == "NOT_SUPPORTED")) for r in rows) and c["negative"] >= 1)
    check("status line", cert["status"] == "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")
    check("no model calls claimed", cert.get("model_calls") == 0)
    check("external review not claimed", cert.get("external_review") == "NOT_OBTAINED")

    fs = sorted(p for p in root.rglob("*") if p.is_file() and "__pycache__" not in p.parts
                and p.name not in ("MANIFEST.json", "GMA_MANIFEST.json", "MERKLE_ROOT.txt",
                                   "GMA_SIGNED_BODY.json", "GMA_VERIFICATION_RESULTS.json",
                                   "GMA_TAMPER_RESULTS.json", "GMA_PUBLIC_CHECK.json",
                                   "PUBLICATION.json", "GMA_OMEGA_SEAL.json", "GMA_PUBKEY.pem"))
    mb = {k: man[k] for k in ("schema", "evolution", "status", "name", "created_at", "verifier",
                              "pubkey_ed25519", "files", "merkle_root", "engine_withheld", "external_review")}
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), canon(mb))
        check("manifest signature", True)
    except Exception:
        check("manifest signature", False)
    check("file hashes match", all(man["files"].get(str(p.relative_to(root))) == sha(p.read_bytes()) for p in fs))
    check("manifest lists exactly the bundle files",
          sorted(man["files"]) == sorted(str(p.relative_to(root)) for p in fs))
    check("merkle root recomputes", man["merkle_root"] == merkle(fs))
    check("manifest binds this certificate",
          man["files"].get("GMA_CERTIFICATE.json") == sha((root / "GMA_CERTIFICATE.json").read_bytes()))
    check("engine source withheld", man.get("engine_withheld") is True and
          not any(p.suffix == ".py" and "verify" not in p.name for p in fs))
    check("external review not claimed in the manifest", man.get("external_review") == "NOT_OBTAINED")

    print(json.dumps({"checks": len(ck), "passed": sum(1 for c_ in ck if c_["ok"]),
                      "failed": fail, "all_valid": cert["all_valid"],
                      "counts": c}, indent=1))
    return 0 if not fail else 1


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