#!/usr/bin/env python3
"""Standalone verifier for CAIN-42 VAGI desk records. Imports no CAIN code; needs only `cryptography`.

    python3 verify_vagi.py record.json [--key <public key hex>]

record.json is the JSON the desk returned ({"record": ..., "record_sha256": ..., "signature_ed25519": ...,
"public_key_ed25519": ...}). Pin the key with --key (published at /api/v1/vagi/key); without --key the key inside
the file is used, which proves integrity but not who signed. Exit 0 = VALID, 1 = INVALID.

It checks: schema; every hash-chain link from the genesis value; the chain head; that each listed action decision
matches its chain event; the record hash; the Ed25519 signature over the canonical record.
"""
import hashlib
import json
import sys

SCHEMA = "cain42.vagi.desk.record.v1"
GENESIS = hashlib.sha256(b"cain42.vagi.desk.v1").hexdigest()


def canonical(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def h(b):
    return hashlib.sha256(b).hexdigest()


def verify(signed, key_hex=None):
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    errs = []
    rec = signed.get("record") or {}
    if rec.get("schema") != SCHEMA:
        errs.append("schema")
    head = GENESIS
    for link in rec.get("chain", []):
        head = h(head.encode() + canonical(link.get("event")))
        if head != link.get("hash"):
            errs.append("chain link")
            break
    if head != rec.get("chain_head"):
        errs.append("chain head")
    evs = [l["event"] for l in rec.get("chain", [])[1:]]
    acts = rec.get("actions", [])
    if len(evs) != len(acts) or any(e.get("decision") != a.get("decision") or e.get("seq") != a.get("seq")
                                    for e, a in zip(evs, acts)):
        errs.append("actions do not match chain")
    if h(canonical(rec)) != signed.get("record_sha256"):
        errs.append("record hash")
    key = key_hex or signed.get("public_key_ed25519", "")
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(key)).verify(
            bytes.fromhex(signed.get("signature_ed25519", "")), canonical(rec))
    except Exception:
        errs.append("signature")
    return errs


def main(argv):
    if len(argv) < 2:
        print(__doc__)
        return 2
    key = argv[argv.index("--key") + 1] if "--key" in argv else None
    with open(argv[1], encoding="utf-8") as fh:
        signed = json.load(fh)
    errs = verify(signed, key)
    rec = signed.get("record", {})
    print(json.dumps({"result": "INVALID" if errs else "VALID", "errors": errs, "desk": rec.get("desk"),
                      "verdict": rec.get("verdict"), "summary": rec.get("summary"),
                      "key_pinned": bool(key), "chain_head": rec.get("chain_head")}, indent=2))
    return 1 if errs else 0


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