#!/usr/bin/env python3
"""
Genesis Forever Memory - Receipt Verifier
Verifies a receipt JSON file is authentic.

Usage:  python3 verify_receipt.py receipt.json
Deps:   pip install pynacl blake3
Exit:   0 = verified, 1 = failed
"""
import json
import sys
from blake3 import blake3
from nacl.signing import VerifyKey
from nacl.exceptions import BadSignatureError

ANCHOR = "fa39bbe8"
PUBKEY = "d6df0e81abe4a58c75963269774ee06c091e277c0efbe168a38a64a7374fe422"
DOM_RECEIPT = b"GENESIS-MEMORY-RECEIPT-v1|"
DOM_CONTENT = b"GENESIS-MEMORY-CONTENT-v1|"
DOMAIN = "FIELD.MEMORY"


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


def verify(receipt):
    # Unwrap if needed
    if isinstance(receipt, dict) and "receipt" in receipt:
        receipt = receipt["receipt"]

    cell = receipt.get("cell", {})
    fp = receipt.get("field_proof", {})
    ar = receipt.get("anti_replay", {})
    sig = receipt.get("signature", {})

    if not all([cell, fp, ar, sig]):
        return False, "schema: missing required fields"

    # Anchor
    if fp.get("constitutional_anchor") != ANCHOR:
        return False, "anchor: mismatch"

    # Domain
    if fp.get("domain") != DOMAIN:
        return False, "domain: not FIELD.MEMORY"

    # Sovereign pubkey
    pubkey = sig.get("server_pubkey", "").replace("ed25519:", "")
    if pubkey.lower() != PUBKEY.lower():
        return False, "sovereign_pubkey: not Genesis sovereign key"

    # Content commitment (if content embedded)
    content = cell.get("content", "")
    stated_cc = cell.get("content_commitment", "").replace("blake3:", "")
    if content:
        h = blake3()
        h.update(DOM_CONTENT)
        h.update(content.encode())
        if h.hexdigest() != stated_cc:
            return False, "content_commitment: content does not match hash"

    # Receipt hash + signature
    cell_signed = {k: v for k, v in cell.items() if k != "content"}
    payload = canonical({
        "cell": cell_signed,
        "field_proof": fp,
        "anti_replay": ar,
    })
    h = blake3()
    h.update(DOM_RECEIPT)
    h.update(payload)
    if h.hexdigest() != sig.get("signed_hash", "").replace("blake3:", ""):
        return False, "receipt_hash: payload tampered"

    sig_hex = sig.get("signature", "").replace("ed25519:", "")
    try:
        VerifyKey(bytes.fromhex(PUBKEY)).verify(
            DOM_RECEIPT + payload,
            bytes.fromhex(sig_hex),
        )
    except BadSignatureError:
        return False, "ed25519_signature: invalid"
    except Exception as e:
        return False, f"ed25519_signature: error: {e}"

    return True, "VERIFIED ALL 7 GATES"


def main():
    if len(sys.argv) != 2:
        print("usage: python3 verify_receipt.py receipt.json")
        sys.exit(2)
    try:
        with open(sys.argv[1]) as f:
            data = json.load(f)
    except FileNotFoundError:
        print(f"FAIL: file not found: {sys.argv[1]}")
        sys.exit(1)
    except json.JSONDecodeError as e:
        print(f"FAIL: not valid JSON: {e}")
        sys.exit(1)

    ok, msg = verify(data)
    if ok:
        print(f"PASS: {msg}")
        sys.exit(0)
    else:
        print(f"FAIL: {msg}")
        sys.exit(1)


if __name__ == "__main__":
    main()
