"""CAIN-A75-053 offline verifier (rules embedded verbatim). CAIN-A75-053 consumer-agent authority rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

A consumer assistant acts for one user across several real services (shopping, transport, travel, deals). The package
claims each service only ever saw a bounded, delegated authority. The review recomputes it:

  grants       each service has its own grant from the named human user, with a purpose, scopes, a spend cap and currency,
               and a validity window; no grant gives full account access
  actions      every action uses the grant for its own service (a grant is never reused on another service), holds the scope
               its kind needs, falls inside the grant's validity, and names the user as the accountable principal
  spend        per grant, the summed amounts in the grant currency stay within its spend cap
  receipts     every booking or purchase carries a receipt bound to it (id, SHA-256, same service, same amount)
  cancellation every booking or purchase records its cancellation and refund path (where to cancel, until when, refundable or
               not); every cancel or refund names an earlier booking on the same service, a refundable one is cancelled
               before its deadline, and a refund never exceeds what was paid
  claims       every boolean the package asserts matches what this review computed

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND.
It reviews the action record; it does not connect to any service or move money.
"""
from __future__ import annotations

import math
import re

_ID = re.compile(r"^[A-Za-z0-9_.:\-/]{1,120}$")
_HEX = re.compile(r"^[0-9a-f]{64}$")
KIND_SCOPE = {"search": "catalog:read", "book": "booking:create", "purchase": "purchase:create",
              "cancel": "booking:cancel", "refund": "refund:request"}
PAID = {"book", "purchase"}


class Bad(ValueError):
    pass


def _num(v, what, lo=0.0, hi=1e15):
    if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or not (lo <= v <= hi):
        raise Bad(f"{what} must be a finite number in [{lo}, {hi}]")
    return float(v)


def _id(v, what):
    if not isinstance(v, str) or not _ID.match(v):
        raise Bad(f"{what} must be an id")
    return v


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

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

    try:
        if not isinstance(record, dict) or record.get("schema") != "cain42.a75.consumeragent.review.v1":
            raise Bad("not a cain42.a75.consumeragent.review.v1 record")
        user = (record.get("user") or {}).get("principal") if isinstance(record.get("user"), dict) else None
        c("user.named_human", isinstance(user, str) and user.startswith("human:") and len(user) > 6, f"user {user!r}")
        grants = record.get("grants")
        if not isinstance(grants, list) or not grants:
            raise Bad("grants must be a non-empty list")
        G, by_service = {}, {}
        for g in grants:
            if not isinstance(g, dict):
                raise Bad("a grant must be an object")
            gid = _id(g.get("id"), "grant.id")
            if gid in G:
                raise Bad(f"duplicate grant {gid}")
            svc = _id(g.get("service"), f"{gid}.service")
            G[gid] = g
            by_service.setdefault(svc, []).append(gid)
            c(f"{gid}.issued_by_user", g.get("issued_by") == user, f"issued by {g.get('issued_by')!r}")
            c(f"{gid}.purpose", isinstance(g.get("purpose"), str) and len(g["purpose"].strip()) >= 3, f"purpose {g.get('purpose')!r}")
            c(f"{gid}.delegated_only", g.get("account_access") == "delegated", f"account access {g.get('account_access')!r}")
            sc = g.get("scopes")
            c(f"{gid}.scopes", isinstance(sc, list) and bool(sc) and set(sc) <= set(KIND_SCOPE.values()), f"scopes {sc!r}")
            c(f"{gid}.window", _num(g.get("issued_at"), f"{gid}.issued_at") < _num(g.get("expires_at"), f"{gid}.expires_at"),
              "non-empty validity window")
            _num(g.get("spend_cap"), f"{gid}.spend_cap")
        for svc, ids in sorted(by_service.items()):
            c(f"service.{svc}.one_grant", len(ids) == 1, f"{len(ids)} grant(s) for {svc}")

        actions = record.get("actions")
        if not isinstance(actions, list) or not actions:
            raise Bad("actions must be a non-empty list")
        A, spent, paid_actions = {}, {}, {}
        for a in sorted((x for x in actions if isinstance(x, dict)),
                        key=lambda x: x.get("at") if isinstance(x.get("at"), (int, float)) and not isinstance(x.get("at"), bool) else 0):
            aid = _id(a.get("id"), "action.id")
            if aid in A:
                raise Bad(f"duplicate action {aid}")
            A[aid] = a
            kind, at = a.get("kind"), _num(a.get("at"), f"{aid}.at")
            if kind not in KIND_SCOPE:
                raise Bad(f"{aid}: unknown kind {kind!r}")
            g = G.get(a.get("grant_id"))
            c(f"{aid}.grant", g is not None, f"grant {a.get('grant_id')!r}")
            c(f"{aid}.accountable", a.get("accountable") == user, f"accountable {a.get('accountable')!r}")
            if g is None:
                continue
            c(f"{aid}.same_service", g.get("service") == a.get("service"),
              f"grant for {g.get('service')!r} used on {a.get('service')!r}")
            c(f"{aid}.scope", KIND_SCOPE[kind] in (g.get("scopes") or []), f"{kind} needs {KIND_SCOPE[kind]}")
            c(f"{aid}.in_window", g["issued_at"] <= at < g["expires_at"], "inside the grant validity")
            if kind in PAID:
                amt = _num(a.get("amount"), f"{aid}.amount")
                c(f"{aid}.currency", a.get("currency") == g.get("currency"), f"currency {a.get('currency')!r}")
                spent[g["id"]] = spent.get(g["id"], 0.0) + amt
                c(f"{aid}.spend_cap", spent[g["id"]] <= g["spend_cap"] + 1e-9,
                  f"grant total {round(spent[g['id']], 2)} <= cap {g['spend_cap']}")
                rc = a.get("receipt") if isinstance(a.get("receipt"), dict) else {}
                c(f"{aid}.receipt", isinstance(rc.get("id"), str) and bool(rc.get("id")) and isinstance(rc.get("sha256"), str)
                  and bool(_HEX.match(rc["sha256"])) and rc.get("service") == a.get("service")
                  and isinstance(rc.get("amount"), (int, float)) and abs(rc["amount"] - amt) <= 0.005,
                  "receipt bound to this action (id, hash, service, amount)")
                cx = a.get("cancellation") if isinstance(a.get("cancellation"), dict) else {}
                ok_cx = (isinstance(cx.get("path"), str) and len(cx["path"]) >= 3 and isinstance(cx.get("refundable"), bool)
                         and (not cx.get("refundable") or (isinstance(cx.get("deadline"), (int, float)) and cx["deadline"] > at)))
                c(f"{aid}.cancellation_path", ok_cx, "cancellation and refund path recorded")
                paid_actions[aid] = {"service": a.get("service"), "amount": amt, "at": at, "cx": cx, "refunded": 0.0}
            if kind in ("cancel", "refund"):
                ref = paid_actions.get(a.get("ref_action"))
                c(f"{aid}.references_booking", ref is not None and ref["service"] == a.get("service") and ref["at"] <= at,
                  f"references {a.get('ref_action')!r}")
                if ref is not None and kind == "cancel" and ref["cx"].get("refundable"):
                    c(f"{aid}.before_deadline", at <= ref["cx"].get("deadline", -1), "cancelled before the refund deadline")
                if ref is not None and kind == "refund":
                    amt = _num(a.get("amount"), f"{aid}.amount")
                    ref["refunded"] += amt
                    c(f"{aid}.refund_bound", ref["refunded"] <= ref["amount"] + 1e-9, f"refunds {ref['refunded']} <= paid {ref['amount']}")
                    c(f"{aid}.refundable", bool(ref["cx"].get("refundable")), "the booking was refundable")
        summary["grants"] = {gid: {"service": G[gid]["service"], "spent": round(spent.get(gid, 0.0), 2)} for gid in G}

        claims = record.get("claims") if isinstance(record.get("claims"), dict) else {}

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

        computed = {
            "per_service_grants": all_ok(lambda i: i.startswith("service.") or (i.split(".")[0] in G and i.split(".", 1)[1] in
                                                                                 ("issued_by_user", "purpose", "delegated_only", "scopes", "window"))),
            "actions_within_grants": all_ok(lambda i: i.split(".", 1)[-1] in ("grant", "same_service", "scope", "in_window",
                                                                              "currency", "spend_cap")),
            "receipts_bound": all_ok(lambda i: i.endswith(".receipt")),
            "cancellation_paths_recorded": all_ok(lambda i: i.endswith((".cancellation_path", ".references_booking",
                                                                        ".before_deadline", ".refund_bound", ".refundable"))),
            "accountable_principal_named": all_ok(lambda i: i.endswith(".accountable") or i == "user.named_human"),
        }
        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["computed"] = computed
    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.consumeragent.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-053, {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))
