"""CAIN-A75-057 offline verifier (rules embedded verbatim). CAIN-A75-022 agent wallet mandate rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

An agent with a wallet needs a mandate, not a card number: who it acts for, where it may pay, how much per payment, how much in
total, how fast, until when, and whether the mandate was revoked. The review replays a wallet's decision log against its mandate:

  mandate      a named human principal, one agent, one currency, a non-empty merchant set, a per-payment ceiling no larger than
               the total budget, a velocity limit and a lifetime; its SHA-256 is recomputed and every decision must cite it
  decisions    each requested payment is recomputed in time order: wrong mandate digest, wrong agent, revoked, outside the
               lifetime, wrong currency, unknown merchant (exact host match, so a look-alike is unknown), invalid amount, over the
               per-payment ceiling, over the velocity limit, over the remaining budget. The recorded decision and reason must
               equal the recomputed ones; anything not allowed is a DENY
  settlement   a payment settled if and only if it was allowed
  published    the published allowed count, denied count and amount spent equal the recomputation
  claims       every boolean the record asserts matches what this review computed

Amounts are integers in the currency's minor unit. Verdict: SOUND, else UNSOUND with every failing check named. Malformed input
is UNSOUND. It reviews the log; it moves no money and contacts no payment network.
"""
from __future__ import annotations

import hashlib
import json
import math

SCHEMA = "cain42.a75.walletmandate.review.v1"
MANDATE_FIELDS = ("id", "principal", "agent", "currency", "merchants", "max_per_transaction", "total_budget", "velocity",
                  "not_before", "expires_at")
MAX_TX = 5000


class Bad(ValueError):
    pass


def mandate_sha256(m):
    """SHA-256 of the mandate's canonical JSON over its authority fields (revocation is state, not part of the digest)."""
    body = {k: m.get(k) for k in MANDATE_FIELDS}
    return hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()).hexdigest()


def _int(v, what, lo=0):
    if isinstance(v, bool) or not isinstance(v, int) or not (lo <= v <= 10 ** 15):
        raise Bad(f"{what} must be an integer (minor units) of at least {lo}")
    return v


def _num(v, what):
    if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or not (0 <= v <= 1e15):
        raise Bad(f"{what} must be a finite, non-negative number")
    return float(v)


def expected_decision(tx, mandate, digest, state):
    """(decision, reason) for one payment request. state = {"spent": int, "allowed_at": [times]} before this request."""
    at = tx["at"]
    if tx.get("mandate_sha256") != digest:
        return "DENY", "wrong_mandate"
    if tx.get("agent") != mandate["agent"]:
        return "DENY", "wrong_agent"
    if mandate.get("revoked_at") is not None and mandate["revoked_at"] <= at:
        return "DENY", "revoked"
    if at < mandate["not_before"]:
        return "DENY", "not_yet_valid"
    if at > mandate["expires_at"]:
        return "DENY", "expired"
    if tx.get("currency") != mandate["currency"]:
        return "DENY", "wrong_currency"
    host = tx.get("merchant")
    if not isinstance(host, str) or host.strip().lower().rstrip(".") not in mandate["merchants"]:
        return "DENY", "unknown_merchant"
    amount = tx.get("amount")
    if isinstance(amount, bool) or not isinstance(amount, int) or amount <= 0:
        return "DENY", "invalid_amount"
    if amount > mandate["max_per_transaction"]:
        return "DENY", "over_per_transaction_limit"
    window = mandate["velocity"]["window_seconds"]
    if sum(1 for t in state["allowed_at"] if at - t < window) >= mandate["velocity"]["max_transactions"]:
        return "DENY", "velocity_exceeded"
    if state["spent"] + amount > mandate["total_budget"]:
        return "DENY", "over_budget"
    return "ALLOW", None


def evaluate(record):
    checks, summary = [], {}

    def c(cid, ok, detail=""):
        checks.append({"id": cid, "ok": bool(ok), "detail": detail})

    try:
        if not isinstance(record, dict) or record.get("schema") != SCHEMA:
            raise Bad(f"not a {SCHEMA} record")
        m, txs = record.get("mandate"), record.get("transactions")
        if not isinstance(m, dict) or not isinstance(txs, list) or not txs or len(txs) > MAX_TX:
            raise Bad(f"a mandate and 1 to {MAX_TX} transactions are required")
        per, total = _int(m.get("max_per_transaction"), "mandate.max_per_transaction", 1), _int(m.get("total_budget"), "mandate.total_budget", 1)
        vel = m.get("velocity")
        if not isinstance(vel, dict):
            raise Bad("mandate.velocity is required")
        _int(vel.get("max_transactions"), "mandate.velocity.max_transactions", 1)
        if _num(vel.get("window_seconds"), "mandate.velocity.window_seconds") <= 0:
            raise Bad("mandate.velocity.window_seconds must be positive")
        nb, exp = _num(m.get("not_before"), "mandate.not_before"), _num(m.get("expires_at"), "mandate.expires_at")
        if m.get("revoked_at") is not None:
            _num(m["revoked_at"], "mandate.revoked_at")
        merchants = m.get("merchants")
        if not isinstance(merchants, list) or not merchants or not all(isinstance(x, str) and x and x == x.strip().lower() for x in merchants):
            raise Bad("mandate.merchants must be a non-empty list of lower-case host names")
        if not isinstance(m.get("currency"), str) or len(m["currency"]) != 3:
            raise Bad("mandate.currency must be a three-letter code")
        digest = mandate_sha256(m)
        c("mandate.principal", isinstance(m.get("principal"), str) and m["principal"].startswith("human:") and len(m["principal"]) > 6
          and isinstance(m.get("agent"), str) and m["agent"].startswith("agent:") and len(m["agent"]) > 6,
          f"principal {m.get('principal')!r}, agent {m.get('agent')!r}")
        c("mandate.limits", per <= total and nb < exp, f"per payment {per}, total {total}, valid {nb}..{exp}")
        c("mandate.digest", record.get("mandate_sha256") == digest, f"stated {str(record.get('mandate_sha256'))[:16]}, recomputed {digest[:16]}")
        ids = set()
        for t in txs:
            if not isinstance(t, dict) or not isinstance(t.get("id"), str) or t["id"] in ids:
                raise Bad("every transaction needs a unique id")
            ids.add(t["id"])
            _num(t.get("at"), f"{t['id']}.at")
        c("transactions.time_ordered", all(txs[i]["at"] <= txs[i + 1]["at"] for i in range(len(txs) - 1)), f"{len(txs)} requests")
        state, tally = {"spent": 0, "allowed_at": []}, {}
        for t in sorted(txs, key=lambda x: x["at"]):
            want, why = expected_decision(t, m, digest, state)
            got = (t.get("decision"), t.get("reason") if t.get("decision") != "ALLOW" else None)
            c(f"tx.{t['id']}.decision", got == (want, why),
              f"recorded {t.get('decision')!r}" + (f" ({t.get('reason')!r})" if t.get("decision") != "ALLOW" else "")
              + f", recomputed {want!r}" + (f" ({why!r})" if why else "") + f" for {t.get('amount')!r} at {t.get('merchant')!r}")
            c(f"tx.{t['id']}.settlement", t.get("settled") is (want == "ALLOW"), f"settled {t.get('settled')!r}, recomputed decision {want!r}")
            if want == "ALLOW":
                state["spent"] += t["amount"]
                state["allowed_at"].append(t["at"])
            tally[why or "ALLOW"] = tally.get(why or "ALLOW", 0) + 1
        pub = record.get("published") if isinstance(record.get("published"), dict) else {}
        want_pub = {"allowed": tally.get("ALLOW", 0), "denied": len(txs) - tally.get("ALLOW", 0), "spent": state["spent"]}
        c("published.totals", all(pub.get(k) == v and not isinstance(pub.get(k), bool) for k, v in want_pub.items()),
          f"stated {[pub.get(k) for k in want_pub]}, recomputed {list(want_pub.values())}")

        def all_ok(pred):
            return all(x["ok"] for x in checks if pred(x["id"]))

        computed = {"mandate_well_formed": all_ok(lambda i: i.startswith("mandate.")),
                    "every_decision_correct": all_ok(lambda i: i.endswith(".decision") or i.startswith("transactions.")),
                    "only_allowed_payments_settled": all_ok(lambda i: i.endswith(".settlement")),
                    "totals_match": all_ok(lambda i: i.startswith("published."))}
        claims = record.get("claims") if isinstance(record.get("claims"), dict) else {}
        for k in sorted(claims):
            c(f"claims.{k}", k in computed and claims[k] == computed[k], f"claimed {claims[k]!r}, computed {computed.get(k)!r}")
        summary.update({"computed": computed, "requests": len(txs), "allowed": want_pub["allowed"], "denied": want_pub["denied"],
                        "spent": state["spent"], "budget_left": total - state["spent"], "currency": m["currency"],
                        "denial_reasons": {k: tally[k] for k in sorted(tally) if k != "ALLOW"}})
    except Bad as e:
        checks.append({"id": "input.well_formed", "ok": False, "detail": str(e)})
        return "UNSOUND", checks, summary
    except Exception as e:  # noqa: BLE001
        checks.append({"id": "input.error", "ok": False, "detail": f"{type(e).__name__}: {e}"[:200]})
        return "UNSOUND", checks, summary
    return ("SOUND" if all(x["ok"] for x in checks) else "UNSOUND"), checks, summary


# ---------------------------------------------------------------------------- offline verifier (no CAIN imports)
# Every name below is prefixed _kit_verifier_ / _b64 / _hl / _json / _sys so it cannot shadow a name in the rules above.
import base64 as _b64, hashlib as _hl, json as _json, sys as _sys
_KIT_VERIFIER_GENESIS = _hl.sha256(b"cain42.a75.commercerefusal.genesis").hexdigest()


def _kit_verifier_canon(o):
    return _json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()


def _kit_verifier_sha(o):
    return _hl.sha256(_kit_verifier_canon(o)).hexdigest()


def _kit_verifier_main(argv):
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    if len(argv) < 2:
        print("usage: verify_offline.py run.json --pinned-key BASE64"); return 2
    run = _json.load(open(argv[1]))
    pin = argv[argv.index("--pinned-key") + 1] if "--pinned-key" in argv else None
    problems, prev, recs = [], _KIT_VERIFIER_GENESIS, run.get("records") or []
    for i, r in enumerate(recs):
        body = {k: v for k, v in r.items() if k not in ("record_hash", "signature_b64")}
        if _kit_verifier_sha(body) != r.get("record_hash"): problems.append(f"record {i}: record_hash does not match")
        if body.get("subject_sha256") != _kit_verifier_sha(body.get("subject")): problems.append(f"record {i}: subject_sha256 does not match")
        if pin and r.get("public_key_b64") != pin: problems.append(f"record {i}: different key than the pinned one")
        try:
            Ed25519PublicKey.from_public_bytes(_b64.b64decode(pin or r.get("public_key_b64"))).verify(
                _b64.b64decode(r.get("signature_b64", "")), str(r.get("record_hash")).encode())
        except Exception:
            problems.append(f"record {i}: signature does not verify")
        if r.get("prev_record_hash") != prev: problems.append(f"record {i}: chain link broken")
        v, checks, _ = evaluate(r.get("subject"))
        if v != r.get("verdict") or checks != r.get("checks"):
            problems.append(f"record {i}: re-running the rules gives {v}, the record says {r.get('verdict')}")
        prev = r.get("record_hash")
    if run.get("run_hash") != _kit_verifier_sha([r.get("record_hash") for r in recs]): problems.append("run_hash does not match")
    for p in problems: print("  -", p)
    if not pin: print("WARNING: no --pinned-key given; the signature was checked against the key inside the file")
    print("VERDICT:", "VERIFIED" if not problems else "TAMPERED OR INVALID", f"(CAIN-A75-057, {len(recs)} record(s), verdicts {run.get('verdicts')})")
    return 0 if not problems else 1


if __name__ == "__main__":
    _sys.exit(_kit_verifier_main(_sys.argv))
