#!/usr/bin/env python3
"""Re-check gaents.com's open numbers yourself. Python 3.8+ stdlib; `pip install cryptography` adds the Ed25519 checks.

  python3 verify.py                       # fetch https://gaents.com/verify/ledger-export.json + stats.json, recompute, compare
  python3 verify.py --export FILE         # same, from a local copy of the export
  python3 verify.py run <quote_id>        # 'prove it' for one call: quote signature, its ledger rows, its call row, chain position
  python3 verify.py anchor <txid> <payload-file>   # does this BSV transaction carry these exact bytes? (raw hex from WhatsOnChain)

What it checks:
  1. head hash: h0 = sha256(chain_tag); h_i = sha256(h_{i-1} + "\\n" + canonical_json(ledger_row_i)) in export order. The last h is the head.
  2. double entry: every txn_id's rows sum to 0, and the whole ledger sums to 0.
  3. quote signatures: each signed quote verifies against the clone's Ed25519 public key (canonical JSON of the quote fields).
  4. every number in stats.json equals the recompute (compute_stats below is the only definition of each number).
  5. anchor: if the export names a BSV txid, the head hash it carries is in that transaction's raw bytes.
Exit code 0 = every check passed; 1 = at least one failed (each printed).
"""
import base64, hashlib, json, sys, urllib.request

BASE = "https://gaents.com"
TX_HEX_URL = "https://api.whatsonchain.com/v1/bsv/main/tx/{txid}/hex"
QUOTE_FIELDS = ("quote_id", "clone_id", "route", "price_usd", "upstream_cost_usd", "max_tokens", "amounts", "ts", "expires_at")


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


def head_chain(rows, tag):
    h = hashlib.sha256(tag.encode()).hexdigest()
    out = []
    for r in rows:
        h = hashlib.sha256((h + "\n" + canonical(r)).encode()).hexdigest()
        out.append(h)
    return out


def _unb64(s):
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))


def verify_quote_sig(pubkey_b64, q):
    """True / False, or None if the quote carries no signature or cryptography is missing."""
    if not q.get("sig"):
        return None
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        from cryptography.exceptions import InvalidSignature
    except ImportError:
        return None
    doc = {k: q[k] for k in QUOTE_FIELDS}
    try:
        Ed25519PublicKey.from_public_bytes(_unb64(pubkey_b64)).verify(_unb64(q["sig"]), json.dumps(doc, sort_keys=True, separators=(",", ":")).encode())
        return True
    except (InvalidSignature, ValueError):
        return False


def compute_stats(exp):
    """Every number on gaents.com/stats/ is defined here and nowhere else."""
    ledger, calls, quotes = exp["ledger"], exp["calls"], exp["quotes"]
    prefix = exp["route_account_prefix"]
    chain = head_chain(ledger, exp["chain_tag"])
    txn = {}
    for r in ledger:
        txn[r["txn_id"]] = txn.get(r["txn_id"], 0) + r["delta_micro"]
    routes = sorted({c["route"] for c in calls if c.get("route")} | {r["agent"][len(prefix):] for r in ledger if r["agent"].startswith(prefix)})
    per_route = {}
    for rt in routes:
        rc = [c for c in calls if c.get("route") == rt]
        paid = [c for c in rc if c.get("outcome") == "paid_ok"]
        pt = sum((c.get("usage") or {}).get("prompt_tokens", 0) for c in paid)
        ct = sum((c.get("usage") or {}).get("completion_tokens", 0) for c in paid)
        outcomes = {}
        for c in rc:
            outcomes[c["outcome"]] = outcomes.get(c["outcome"], 0) + 1
        per_route[rt] = {"calls": len(rc), "paid_ok_calls": len(paid), "outcomes": outcomes,
                         "prompt_tokens": pt, "completion_tokens": ct,
                         "spend_micro_usd": sum(r["delta_micro"] for r in ledger if r["agent"] == prefix + rt),
                         "distinct_payers": len({c.get("who") for c in paid if c.get("who")})}
    by_class = {}
    for r in ledger:
        if r["delta_micro"] > 0:
            by_class[r["classification"]] = by_class.get(r["classification"], 0) + r["delta_micro"]
    sigs = [verify_quote_sig(exp["signing_pubkey"], q) for q in quotes]
    payers = {}
    for c in calls:
        w = c.get("who")
        if not w:
            continue
        p = payers.setdefault(w, {"calls": 0, "paid_ok_calls": 0, "other_outcome_calls": 0, "routes": set()})
        p["calls"] += 1
        p["paid_ok_calls" if c.get("outcome") == "paid_ok" else "other_outcome_calls"] += 1
        p["routes"].add(c.get("route"))
    for w, p in payers.items():
        p["routes"] = sorted(p["routes"])
        p["spend_micro_usd"] = -sum(r["delta_micro"] for r in ledger if r["agent"] == w and r["kind"] in ("debit", "refund", "reversal"))
        p["topped_up_micro_usd"] = sum(r["delta_micro"] for r in ledger if r["agent"] == w and r["kind"] == "topup")
    return {
        "ledger_rows": len(ledger),
        "txns": len(txn),
        "unbalanced_txns": sum(1 for v in txn.values() if v != 0),
        "ledger_sum_micro_usd": sum(r["delta_micro"] for r in ledger),
        "head_hash": chain[-1] if chain else None,
        "calls": len(calls),
        "paid_ok_calls": sum(1 for c in calls if c.get("outcome") == "paid_ok"),
        "calls_by_payer_classification": _count(c.get("classification") or "none (no payment)" for c in calls),
        "external_rail_payments": sum(1 for e in exp["payment_events"] if e["event"] == "consumed" and e["verifier"] != "internal_balance"),
        "credited_micro_usd_by_classification": by_class,
        "quotes": len(quotes),
        "quotes_signed": sum(1 for q in quotes if q.get("sig")),
        "quote_signatures_valid": sum(1 for s in sigs if s is True),
        "quote_signatures_invalid": sum(1 for s in sigs if s is False),
        "alarms": exp["alarms"],
        "per_route": per_route,
        "payers": payers,
    }


def _count(it):
    d = {}
    for x in it:
        d[x] = d.get(x, 0) + 1
    return d


def _get(url):
    with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "gaents-verify"}), timeout=30) as r:
        return r.read()


def check_anchor(txid, payload_bytes):
    raw = _get(TX_HEX_URL.format(txid=txid)).decode().strip()
    return payload_bytes.hex() in raw


def main(argv):
    exp_path = None
    if "--export" in argv:
        i = argv.index("--export"); exp_path = argv[i + 1]; del argv[i:i + 2]
    if argv and argv[0] == "anchor":
        ok = check_anchor(argv[1], open(argv[2], "rb").read())
        print("anchor", argv[1], "carries the payload byte-for-byte:", ok)
        return 0 if ok else 1
    exp = json.load(open(exp_path)) if exp_path else json.loads(_get(BASE + "/verify/ledger-export.json"))
    if argv and argv[0] == "run":
        qid = argv[1]
        q = next((q for q in exp["quotes"] if q["quote_id"] == qid), None)
        if not q:
            print("no quote", qid); return 1
        chain = head_chain(exp["ledger"], exp["chain_tag"])
        print("quote:", canonical({k: q.get(k) for k in (*QUOTE_FIELDS, "sig")}))
        print("signature valid:", verify_quote_sig(exp["signing_pubkey"], q), "(None = unsigned quote or cryptography missing)")
        for i, r in enumerate(exp["ledger"]):
            if r.get("ref") == qid:
                print(f"ledger row {i}: {canonical(r)}\n  chain hash after this row: {chain[i]}")
        for c in exp["calls"]:
            if c.get("quote_id") == qid:
                print("call:", canonical(c))
        return 0
    got = compute_stats(exp)
    published = json.loads(_get(BASE + "/verify/stats.json")) if not exp_path else None
    fails = 0
    def check(name, ok, detail=""):
        nonlocal fails
        fails += 0 if ok else 1
        print(("PASS " if ok else "FAIL ") + name + (f"  {detail}" if detail else ""))
    check("double entry: every txn sums to 0", got["unbalanced_txns"] == 0, f"{got['unbalanced_txns']} unbalanced")
    check("ledger total is 0", got["ledger_sum_micro_usd"] == 0, str(got["ledger_sum_micro_usd"]))
    check("export head hash matches recompute", exp.get("head_hash") == got["head_hash"], got["head_hash"] or "")
    check("no invalid quote signature", got["quote_signatures_invalid"] == 0,
          f"{got['quote_signatures_valid']} valid of {got['quotes_signed']} signed, {got['quotes']} quotes")
    if published is not None:
        pub = published["stats"]
        diffs = [k for k in got if canonical(got[k]) != canonical(pub.get(k))]
        check("stats.json equals recompute", not diffs, "differs: " + ",".join(diffs) if diffs else "")
    anc = exp.get("anchor") or {}
    if anc.get("txid"):
        check("head hash anchored on BSV", check_anchor(anc["txid"], anc["payload"].encode()), anc["txid"])
    else:
        print("OPEN anchor: this ledger has not been anchored on BSV yet (export.anchor.txid is null)")
    return 1 if fails else 0


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