"""CAIN-A75-047 offline verifier (rules embedded verbatim). CAIN-A75-047 commerce-protocol authority rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

A shopping agent ran one session from discovery to purchase to post-purchase support. The package claims each phase used
only the authority it needed. The review recomputes it:

  mandate     the purchase mandate was issued by the session's human principal, with a merchant allowlist, per-payment and
              total caps, a currency, a velocity limit and a validity window
  phases      phases run in order (discovery, checkout, post_purchase), in non-overlapping time; each carries only the scopes
              its phase allows; only checkout carries the mandate; each handoff names the previous phase and its SHA-256
  actions     every action runs inside its phase's window and holds the scope its kind needs
  payment     every payment is in checkout, to an allowlisted merchant, in the mandate currency, within the per-payment cap,
              the running total and the velocity window, and inside the mandate's validity
  returns     every return or refund names an order paid in this session and never exceeds what was paid for it
  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 session record; it does not talk to a merchant, a wallet or a payment network.
"""
from __future__ import annotations

import hashlib
import json
import math
import re

_ID = re.compile(r"^[A-Za-z0-9_.:\-/]{1,120}$")
PHASE_ORDER = ["discovery", "checkout", "post_purchase"]
PHASE_SCOPES = {"discovery": {"catalog:read", "search:read"},
                "checkout": {"cart:write", "payment:mandate", "address:read"},
                "post_purchase": {"order:read", "return:create", "support:message"}}
KIND_SCOPE = {"search": "search:read", "view": "catalog:read", "add_to_cart": "cart:write", "pay": "payment:mandate",
              "read_address": "address:read", "order_status": "order:read", "return": "return:create",
              "message": "support:message"}


class Bad(ValueError):
    pass


def phase_hash(phase):
    return hashlib.sha256(json.dumps(phase, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()).hexdigest()


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 = [], {"phases": {}, "payments": [], "returns": []}

    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.commerce.session.v1":
            raise Bad("not a cain42.a75.commerce.session.v1 record")
        sess, m = record.get("session"), record.get("mandate")
        if not isinstance(sess, dict) or not isinstance(m, dict):
            raise Bad("session and mandate must be objects")
        principal = sess.get("principal")
        mid = _id(m.get("id"), "mandate.id")
        m_from = _num(m.get("issued_at"), "mandate.issued_at")
        m_to = _num(m.get("expires_at"), "mandate.expires_at")
        cap = _num(m.get("max_amount"), "mandate.max_amount")
        total_cap = _num(m.get("max_total"), "mandate.max_total")
        max_tx = int(_num(m.get("max_payments"), "mandate.max_payments", 1, 1000))
        window = _num(m.get("velocity_window_s"), "mandate.velocity_window_s", 1.0, 1e9)
        merchants = m.get("merchants")
        if not isinstance(merchants, list) or not merchants:
            raise Bad("mandate.merchants must be a non-empty allowlist")
        c("mandate.principal", isinstance(principal, str) and principal.startswith("human:") and m.get("issued_by") == principal,
          f"issued by {m.get('issued_by')!r}, principal {principal!r}")
        c("mandate.validity", m_from < m_to, "validity window is non-empty")
        c("mandate.caps", cap <= total_cap, f"per-payment cap {cap} <= total cap {total_cap}")

        phases = record.get("phases")
        if not isinstance(phases, list) or not phases:
            raise Bad("phases must be a non-empty list")
        P, prev, last_rank = {}, None, -1
        for ph in phases:
            if not isinstance(ph, dict):
                raise Bad("a phase must be an object")
            pid = _id(ph.get("id"), "phase.id")
            if pid in P:
                raise Bad(f"duplicate phase {pid}")
            kind = ph.get("phase")
            if kind not in PHASE_ORDER:
                raise Bad(f"{pid}: unknown phase {kind!r}")
            start, end = _num(ph.get("started_at"), f"{pid}.started_at"), _num(ph.get("ended_at"), f"{pid}.ended_at")
            scopes = ph.get("scopes")
            if not isinstance(scopes, list):
                raise Bad(f"{pid}.scopes must be a list")
            extra = sorted(set(scopes) - PHASE_SCOPES[kind])
            c(f"{pid}.scopes", not extra, f"{kind} scopes beyond its phase: {extra}" if extra else f"{kind} scopes only")
            c(f"{pid}.mandate", (ph.get("mandate_id") == mid) if kind == "checkout" else ph.get("mandate_id") in (None, ""),
              f"{kind} carries mandate {ph.get('mandate_id')!r}")
            c(f"{pid}.window", start <= end, "phase window is non-empty")
            rank = PHASE_ORDER.index(kind)
            c(f"{pid}.order", rank >= last_rank, f"{kind} after {PHASE_ORDER[last_rank] if last_rank >= 0 else 'start'}")
            if prev is None:
                c(f"{pid}.handoff", ph.get("handoff_from") in (None, ""), "first phase has no handoff")
            else:
                c(f"{pid}.handoff", ph.get("handoff_from") == prev.get("id") and ph.get("handoff_sha256") == phase_hash(prev),
                  f"handoff from {prev.get('id')} bound to its hash")
                c(f"{pid}.no_overlap", start >= _num(prev.get("ended_at"), "ended_at"), "starts after the previous phase ended")
            last_rank = max(last_rank, rank)
            P[pid] = {"kind": kind, "start": start, "end": end, "scopes": set(scopes)}
            summary["phases"][pid] = {"phase": kind, "scopes": sorted(scopes)}
            prev = ph

        actions = record.get("actions")
        if not isinstance(actions, list) or not actions:
            raise Bad("actions must be a non-empty list")
        A, paid, pay_times, total = set(), {}, [], 0.0
        refunded = {}
        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)) else 0)):
            aid = _id(a.get("id"), "action.id")
            if aid in A:
                raise Bad(f"duplicate action {aid}")
            A.add(aid)
            kind, pid, at = a.get("kind"), a.get("phase_id"), _num(a.get("at"), f"{aid}.at")
            if kind not in KIND_SCOPE:
                raise Bad(f"{aid}: unknown action kind {kind!r}")
            if pid not in P:
                c(f"{aid}.phase", False, f"unknown phase {pid!r}")
                continue
            ph = P[pid]
            c(f"{aid}.in_phase", ph["start"] <= at <= ph["end"], f"at {at} inside {pid}")
            c(f"{aid}.scope", KIND_SCOPE[kind] in ph["scopes"], f"{kind} needs {KIND_SCOPE[kind]} in {pid}")
            if kind == "pay":
                amt = _num(a.get("amount"), f"{aid}.amount")
                oid = _id(a.get("order_id"), f"{aid}.order_id")
                c(f"{aid}.pay.checkout", ph["kind"] == "checkout", "payment only in checkout")
                c(f"{aid}.pay.mandate", a.get("mandate_id") == mid, "payment cites the session mandate")
                c(f"{aid}.pay.merchant", a.get("merchant") in merchants, f"merchant {a.get('merchant')!r}")
                c(f"{aid}.pay.currency", a.get("currency") == m.get("currency"), f"currency {a.get('currency')!r}")
                c(f"{aid}.pay.cap", amt <= cap + 1e-9, f"{amt} <= per-payment cap {cap}")
                total += amt
                c(f"{aid}.pay.total", total <= total_cap + 1e-9, f"running total {round(total, 2)} <= {total_cap}")
                pay_times.append(at)
                recent = [t for t in pay_times if at - t < window]
                c(f"{aid}.pay.velocity", len(recent) <= max_tx, f"{len(recent)} payment(s) in {window}s <= {max_tx}")
                c(f"{aid}.pay.valid", m_from <= at <= m_to, "inside the mandate validity")
                c(f"{aid}.pay.unique_order", oid not in paid, f"order {oid} paid once")
                paid[oid] = paid.get(oid, 0.0) + amt
                summary["payments"].append({"id": aid, "amount": amt, "merchant": a.get("merchant")})
            if kind == "return":
                oid = a.get("order_id")
                amt = _num(a.get("refund_amount"), f"{aid}.refund_amount")
                c(f"{aid}.return.order", oid in paid, f"order {oid!r} was paid in this session")
                refunded[oid] = refunded.get(oid, 0.0) + amt
                c(f"{aid}.return.amount", oid in paid and refunded[oid] <= paid[oid] + 1e-9,
                  f"refunds {refunded[oid]} <= paid {paid.get(oid)}")
                summary["returns"].append({"id": aid, "order_id": oid, "amount": amt})
        summary["total_paid"] = round(total, 2)

        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 = {
            "phase_scoped": all_ok(lambda i: i.endswith((".scopes", ".mandate", ".scope", ".phase", ".in_phase"))
                                   and not i.startswith("mandate.")),
            "mandate_only_in_checkout": all_ok(lambda i: i.endswith(".mandate") and not i.startswith("mandate.")),
            "payments_within_mandate": all_ok(lambda i: ".pay." in i or i.startswith("mandate.")),
            "handoffs_recorded": all_ok(lambda i: i.endswith((".handoff", ".order", ".no_overlap", ".window")) and ".return." not in i),
            "returns_bounded": all_ok(lambda i: ".return." in i),
        }
        for key in sorted(claims):
            c(f"claims.{key}", key in computed and claims[key] == computed[key], f"claimed {claims[key]!r}, computed {computed.get(key)!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.commerce.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-047, {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))
