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

An agent can complete a checkout without ever holding the card. A broker keeps the credential; the agent states an intent; the
broker releases a single-use token bound to that exact merchant origin, amount and cart; the merchant redeems it. The review
recomputes a checkout log against the mandate:

  mandate      a named human principal, one agent, one currency, exact https merchant origins, a per-checkout ceiling, a
               step-up threshold and a lifetime; the broker is a named service the agent cannot read the credential from
  decision     each checkout is recomputed: unknown origin (exact scheme and host, so a look-alike or a non-https origin is
               unknown), wrong currency, invalid amount, over the ceiling, outside the lifetime, or above the step-up threshold
               without the principal's approval of that exact cart shortly before. Anything else is RELEASED. The recorded
               decision and reason must equal the recomputed ones
  release      a released checkout has a token that is unique, single-use, short-lived and bound to the same origin, amount and
               cart digest as the intent; a refused checkout has no token and no redemption
  redemption   a token is redeemed at most once, by the bound origin, for the bound amount and cart, inside its lifetime
  no card      nothing the agent could see contains a card number (13 to 19 digits passing the Luhn check) or a labelled
               security code
  published    released and refused counts and the amount released equal the recomputation; claims match

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

import math
import re
from urllib.parse import urlsplit

SCHEMA = "cain42.a75.checkoutmandate.review.v2"
_HEX = re.compile(r"^[0-9a-f]{64}$")
_PAN = re.compile(r"(?<!\d)(?:\d[ -]?){12,18}\d(?!\d)")
_CVV = re.compile(r"(?i)\b(cvv2?|cvc2?|cid|security code)\b\D{0,12}\d{3,4}(?!\d)")
MAX_TOKEN_LIFE, STEP_UP_WINDOW, MAX_CHECKOUTS = 300.0, 600.0, 2000


class Bad(ValueError):
    pass


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 _int(v, what):
    if isinstance(v, bool) or not isinstance(v, int) or not (1 <= v <= 10 ** 15):
        raise Bad(f"{what} must be a positive integer (minor units)")
    return v


def origin(url):
    """Canonical https origin of a URL, or None. User-info, non-https schemes and malformed hosts are rejected."""
    if not isinstance(url, str):
        return None
    try:
        u = urlsplit(url.strip())
        port = u.port
    except ValueError:
        return None
    if u.scheme != "https" or not u.hostname or u.username is not None or u.password is not None:
        return None
    host = u.hostname.lower().rstrip(".")
    return f"https://{host}" + (f":{port}" if port not in (None, 443) else "")


def luhn(digits):
    total, alt = 0, False
    for ch in reversed(digits):
        d = ord(ch) - 48
        if alt:
            d = d * 2 - 9 if d > 4 else d * 2
        total += d
        alt = not alt
    return total % 10 == 0


def card_data_in(text):
    """Names of the kinds of card data found in one string the agent could see."""
    found = []
    if not isinstance(text, str):
        return ["non_text"]
    for m in _PAN.finditer(text):
        digits = re.sub(r"\D", "", m.group(0))
        if 13 <= len(digits) <= 19 and luhn(digits) and len(set(digits)) > 1:
            found.append("card_number")
            break
    if _CVV.search(text):
        found.append("security_code")
    return found


def expected_decision(ck, mandate):
    """(decision, reason) the broker must give this checkout intent."""
    it = ck.get("intent") if isinstance(ck.get("intent"), dict) else {}
    at = ck["at"]
    o = origin(it.get("origin"))
    if o is None or o not in mandate["_origins"]:
        return "REFUSED", "unknown_origin"
    if it.get("currency") != mandate["currency"]:
        return "REFUSED", "wrong_currency"
    amount = it.get("amount")
    if isinstance(amount, bool) or not isinstance(amount, int) or amount <= 0 or not _HEX.match(str(it.get("cart_sha256"))):
        return "REFUSED", "invalid_intent"
    if amount > mandate["max_per_checkout"]:
        return "REFUSED", "over_limit"
    if at < mandate["not_before"] or at > mandate["expires_at"]:
        return "REFUSED", "mandate_not_valid"
    if amount > mandate["step_up_above"]:
        su = ck.get("step_up") if isinstance(ck.get("step_up"), dict) else {}
        s_at = su.get("at")
        ok = su.get("by") == mandate["principal"] and su.get("cart_sha256") == it.get("cart_sha256") and su.get("amount") == amount \
            and isinstance(s_at, (int, float)) and not isinstance(s_at, bool) and at - STEP_UP_WINDOW <= s_at <= at
        if not ok:
            return "REFUSED", "step_up_required"
    return "RELEASED", 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, br, cks = record.get("mandate"), record.get("broker"), record.get("checkouts")
        if not isinstance(m, dict) or not isinstance(br, dict) or not isinstance(cks, list) or not cks or len(cks) > MAX_CHECKOUTS:
            raise Bad(f"mandate, broker and 1 to {MAX_CHECKOUTS} checkouts are required")
        m = dict(m)
        _int(m.get("max_per_checkout"), "mandate.max_per_checkout"); _int(m.get("step_up_above"), "mandate.step_up_above")
        _num(m.get("not_before"), "mandate.not_before"); _num(m.get("expires_at"), "mandate.expires_at")
        if not isinstance(m.get("currency"), str) or len(m["currency"]) != 3:
            raise Bad("mandate.currency must be a three-letter code")
        mer = m.get("merchants")
        if not isinstance(mer, list) or not mer:
            raise Bad("mandate.merchants must be a non-empty list of https origins")
        m["_origins"] = {origin(x) for x in mer}
        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 and m["not_before"] < m["expires_at"],
          f"principal {m.get('principal')!r}, agent {m.get('agent')!r}")
        c("mandate.origins", None not in m["_origins"] and all(origin(x) == x for x in mer),
          f"{len(mer)} merchant origins; each must be a bare https origin")
        c("broker.isolated", isinstance(br.get("name"), str) and br["name"].startswith("service:") and len(br["name"]) > 8
          and br.get("agent_can_read_credential") is False, f"broker {br.get('name')!r}, agent can read credential: {br.get('agent_can_read_credential')!r}")
        ids, tokens = set(), {}
        for ck in cks:
            if not isinstance(ck, dict) or not isinstance(ck.get("id"), str) or ck["id"] in ids:
                raise Bad("every checkout needs a unique id")
            ids.add(ck["id"])
            _num(ck.get("at"), f"{ck['id']}.at")
            rel = ck.get("release")
            if isinstance(rel, dict) and isinstance(rel.get("token"), str):
                tokens.setdefault(rel["token"], []).append(ck["id"])
        released = refused = amount_released = 0
        exposures = 0
        for ck in cks:
            k, it = f"checkout.{ck['id']}", ck.get("intent") if isinstance(ck.get("intent"), dict) else {}
            want, why = expected_decision(ck, m)
            got = (ck.get("decision"), ck.get("reason") if ck.get("decision") != "RELEASED" else None)
            c(f"{k}.decision", ck.get("agent") == m.get("agent") and got == (want, why),
              f"recorded {ck.get('decision')!r}" + (f" ({ck.get('reason')!r})" if ck.get("decision") != "RELEASED" else "")
              + f", recomputed {want!r}" + (f" ({why!r})" if why else "") + f" for {it.get('amount')!r} at {it.get('origin')!r} by {ck.get('agent')!r}")
            rel, red = ck.get("release"), ck.get("redemption")
            if want == "RELEASED":
                released += 1
                amount_released += it["amount"]
                ok_rel = isinstance(rel, dict) and isinstance(rel.get("token"), str) and len(rel["token"]) >= 32 and len(tokens.get(rel["token"], [])) == 1 \
                    and rel.get("single_use") is True and origin(rel.get("bound_origin")) == origin(it.get("origin")) \
                    and rel.get("bound_amount") == it["amount"] and rel.get("bound_cart_sha256") == it.get("cart_sha256") \
                    and isinstance(rel.get("issued_at"), (int, float)) and isinstance(rel.get("expires_at"), (int, float)) \
                    and not isinstance(rel.get("issued_at"), bool) and not isinstance(rel.get("expires_at"), bool) \
                    and ck["at"] <= rel["issued_at"] < rel["expires_at"] <= rel["issued_at"] + MAX_TOKEN_LIFE
                c(f"{k}.release_bound", ok_rel, "no token released" if not isinstance(rel, dict) else
                  f"token bound to {rel.get('bound_origin')!r}, {rel.get('bound_amount')!r}, life {rel.get('issued_at')!r}..{rel.get('expires_at')!r}"
                  + (", token reused by another checkout" if len(tokens.get(rel.get("token"), [])) > 1 else ""))
                if red is not None:
                    ok_red = ok_rel and isinstance(red, dict) and red.get("token") == rel["token"] and origin(red.get("origin")) == origin(rel["bound_origin"]) \
                        and red.get("amount") == rel["bound_amount"] and red.get("cart_sha256") == rel["bound_cart_sha256"] \
                        and isinstance(red.get("at"), (int, float)) and not isinstance(red.get("at"), bool) \
                        and rel["issued_at"] <= red["at"] <= rel["expires_at"] and red.get("times_redeemed") == 1
                    c(f"{k}.redemption", ok_red, f"redeemed by {red.get('origin')!r} for {red.get('amount')!r} at {red.get('at')!r}, "
                      f"{red.get('times_redeemed')!r} time(s)" if isinstance(red, dict) else "malformed redemption")
            else:
                refused += 1
                c(f"{k}.nothing_released", rel is None and red is None, "a refused checkout must have no token and no redemption"
                  if (rel is not None or red is not None) else "no token, no redemption")
            seen = ck.get("agent_visible")
            kinds = sorted({x for s in seen for x in card_data_in(s)}) if isinstance(seen, list) else ["missing"]
            exposures += bool(kinds)
            c(f"{k}.no_card_exposed", not kinds, f"agent-visible data contains {kinds}" if kinds else f"{len(seen)} agent-visible strings, no card data")
        pub = record.get("published") if isinstance(record.get("published"), dict) else {}
        want_pub = {"released": released, "refused": refused, "amount_released": amount_released}
        c("published.totals", all(pub.get(x) == y and not isinstance(pub.get(x), bool) for x, y in want_pub.items()),
          f"stated {[pub.get(x) for x 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_and_broker_sound": all_ok(lambda i: i.startswith(("mandate.", "broker."))),
                    "every_decision_correct": all_ok(lambda i: i.endswith(".decision")),
                    "tokens_bound_and_single_use": all_ok(lambda i: i.endswith((".release_bound", ".redemption", ".nothing_released"))),
                    "card_never_visible_to_agent": all_ok(lambda i: i.endswith(".no_card_exposed")),
                    "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, "checkouts": len(cks), "released": released, "refused": refused,
                        "amount_released": amount_released, "currency": m["currency"], "card_exposures": exposures})
    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.checkoutmandate.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-048, {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))
