#!/usr/bin/env python3
"""demo.py — ACR-1 self-verification. Run: python3 demo.py

1. RFC 8032 Ed25519 test vectors (correctness of the crypto itself)
2. Issue + verify a claim receipt (commit-SHA binding)
3. Tamper rejection (modified ref, swapped pubkey)
4. Chain anchor (receipt 2 anchors receipt 1 hash)
5. Counterparty countersign + verify
"""
import copy
import json

import ed25519
import receipt

PASS = True


def check(name, cond, extra=""):
    global PASS
    PASS = PASS and cond
    print(("  OK  " if cond else "  FAIL") + f" {name}" + (f" — {extra}" if extra else ""))


def rfc8032():
    print("== RFC 8032 test vectors ==")
    # TEST 1: empty message
    sk = bytes.fromhex("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60")
    pk = "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"
    sig = "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"
    check("vector1 pubkey", ed25519.publickey(sk).hex() == pk)
    check("vector1 sign", ed25519.sign(b"", sk).hex() == sig)
    check("vector1 verify", ed25519.verify(bytes.fromhex(sig), b"", bytes.fromhex(pk)))
    # TEST 2: 1-byte message 0x72
    sk2 = bytes.fromhex("4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb")
    pk2 = "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c"
    sig2 = ("92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da"
            "085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00")
    check("vector2 pubkey", ed25519.publickey(sk2).hex() == pk2)
    check("vector2 sign", ed25519.sign(b"\x72", sk2).hex() == sig2)
    check("vector2 verify", ed25519.verify(bytes.fromhex(sig2), b"\x72", bytes.fromhex(pk2)))
    # TEST 3: 2-byte message 0xaf82
    sk3 = bytes.fromhex("c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7")
    pk3 = "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025"
    sig3 = ("6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac"
            "18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a")
    check("vector3 pubkey", ed25519.publickey(sk3).hex() == pk3)
    check("vector3 verify", ed25519.verify(bytes.fromhex(sig3), b"\xaf\x82", bytes.fromhex(pk3)))


def scenario():
    print("== ACR-1 issue / verify ==")
    seed_a = receipt.generate_seed().hex()
    seed_b = receipt.generate_seed().hex()

    r1 = receipt.issue(
        "ARION", seed_a, "commit-set",
        ["f6da12e82a1719e6479357e10a0126f53afec208",
         "698839e92e8660e0d61fe4c2bdd0ed14ede9b463"],
        "Authored the listed upstream commits (agenticjobs PRs #204, #197).",
        anchors=["settlement-invoice:4902083c"])
    ok, why = receipt.verify(r1)
    check("issue+verify", ok, why)
    print("   key_id:", r1["issuer"]["key_id"], "sig:", r1["signature"][:24] + "...")

    print("== tamper rejection ==")
    bad1 = copy.deepcopy(r1)
    bad1["subject"]["refs"].append("0" * 40)
    ok, why = receipt.verify(bad1)
    check("modified refs rejected", not ok, why)
    bad2 = copy.deepcopy(r1)
    bad2["issuer"]["pubkey"] = ed25519.publickey(bytes.fromhex(seed_b)).hex()
    ok, why = receipt.verify(bad2)
    check("swapped pubkey rejected", not ok, why)
    bad3 = copy.deepcopy(r1)
    bad3["claim"] = bad3["claim"] + " (and also unrelated work)"
    ok, why = receipt.verify(bad3)
    check("modified claim rejected", not ok, why)

    print("== chain anchor ==")
    r2 = receipt.issue("ARION", seed_a, "settlement",
                       ["invoice-4902083c"],
                       "First claim-set settled; anchors the prior claim receipt.",
                       anchors=[receipt.receipt_hash(r1)])
    ok, why = receipt.verify(r2)
    check("chained receipt verifies", ok, why)
    check("anchor resolves to r1", receipt.check_anchor(r2, r1))

    print("== countersign (two-party attestation) ==")
    r1c = receipt.countersign(r1, "platform-agenticjobs", seed_b)
    ok, why = receipt.verify(r1c)
    check("issuer sig still valid after countersign", ok, why)
    ok, why = receipt.verify_countersig(r1c)
    check("countersig verifies", ok, why)
    bad4 = copy.deepcopy(r1c)
    bad4["subject"]["refs"] = []
    ok, why = receipt.verify_countersig(bad4)
    check("post-countersig tamper rejected", not ok, why)

    print("\nResult:", "PASS" if PASS else "FAIL")
    return PASS


if __name__ == "__main__":
    rfc8032()
    import sys
    sys.exit(0 if scenario() else 1)
