"""CAIN-A75-066 offline verifier (rules embedded verbatim). CAIN-A75-066 browser errand rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

A mobile browser agent running a real-world errand may spend money, accept terms or create a booking. It needs a bounded task,
a payment ceiling and a clear stop before it commits. Declare the errand's bounds before browsing: sites, spend, time and
acceptable commitments. The review recomputes an errand record:

  declaration  a named human declared the sites, the spend ceiling and currency, the deadline and the allowed commitment
               types before the first action
  bounds       every action happens on a declared site, before the deadline
  commitments  checkout (purchase), book (booking), accept_terms (terms_acceptance), subscribe (subscription) and
               create_account (account_signup) are commitments; any unknown kind is treated as a commitment of an
               undeclared type (fail closed). A commitment's type must be declared
  pause        every commitment was preceded by a pause after the previous action in which a named human confirmed it,
               seeing the exact amount (and, for terms, the terms hash; for a subscription, the recurring amount); a
               declined pause means nothing after it may commit to the same thing
  spend        payments are in the declared currency and their running total stays within the ceiling
  receipts     every purchase, booking and subscription carries a receipt id and the same amount
  claims       every boolean the errand record asserts matches what this review computed

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND. It reviews the errand record; it does
not browse, pay or contact a merchant.
"""
from __future__ import annotations

import math
import re

_ID = re.compile(r"^[A-Za-z0-9_.:\-/@]{1,120}$")
COMMIT = {"checkout": "purchase", "book": "booking", "accept_terms": "terms_acceptance", "subscribe": "subscription",
          "create_account": "account_signup"}
NONCOMMIT = ("browse", "search", "read", "fill", "add_to_cart", "compare")
PAID = ("checkout", "book", "subscribe")


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 _human(p):
    return isinstance(p, str) and p.startswith("human:") and len(p) > 6


def commitment_type(kind):
    if kind in NONCOMMIT:
        return None
    return COMMIT.get(kind, "undeclared:" + str(kind))


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") != "cain42.a75.errand.review.v1":
            raise Bad("not a cain42.a75.errand.review.v1 record")
        d = record.get("declaration")
        if not isinstance(d, dict):
            raise Bad("declaration must be an object")
        sites, allowed = d.get("sites"), d.get("commitments_allowed")
        if not isinstance(sites, list) or not sites or not isinstance(allowed, list):
            raise Bad("declaration needs sites and commitments_allowed lists")
        ceiling = _num(d.get("spend_ceiling"), "declaration.spend_ceiling")
        deadline, dat = _num(d.get("deadline"), "declaration.deadline"), _num(d.get("declared_at"), "declaration.declared_at")
        actions = record.get("actions")
        if not isinstance(actions, list) or not actions or not all(isinstance(a, dict) for a in actions):
            raise Bad("actions must be a non-empty list of objects")
        first = _num(actions[0].get("at"), "action 1.at")
        c("declaration.by_human", _human(d.get("declared_by")), f"declared by {d.get('declared_by')!r}")
        c("declaration.before_browsing", dat < first and deadline > dat, f"declared at {dat:g}, first action {first:g}, deadline {deadline:g}")

        spent, last_at, declined, n_commit, paid = 0.0, -1.0, set(), 0, []
        for k, a in enumerate(actions, start=1):
            aid, at, kind = f"action.{k}", _num(a.get("at"), f"action {k}.at"), a.get("kind")
            if at < last_at:
                raise Bad("actions must be in time order")
            c(f"{aid}.site", a.get("origin") in sites, f"{kind!r} on {a.get('origin')!r}")
            c(f"{aid}.deadline", at <= deadline, f"at {at:g}, deadline {deadline:g}")
            if kind == "pause":
                conf = a.get("decision")
                if conf not in ("confirmed", "declined"):
                    raise Bad(f"{aid}: a pause needs decision confirmed or declined")
                if conf == "declined":
                    declined.add((a.get("for_kind"), a.get("amount")))
                last_at = at
                continue
            ct = commitment_type(kind)
            if ct is not None:
                n_commit += 1
                c(f"{aid}.declared_type", ct in allowed, f"{kind!r} is a {ct!r} commitment; declared {allowed}")
                prev = actions[k - 2] if k >= 2 else {}
                amt = a.get("amount", 0)
                ok_pause = prev.get("kind") == "pause" and prev.get("decision") == "confirmed" and _human(prev.get("confirmed_by")) \
                    and prev.get("for_kind") == kind and prev.get("amount") == amt and isinstance(prev.get("at"), (int, float)) \
                    and prev["at"] < at
                if kind == "accept_terms":
                    ok_pause = ok_pause and isinstance(a.get("terms_sha256"), str) and prev.get("terms_sha256") == a.get("terms_sha256")
                if kind == "subscribe":
                    ok_pause = ok_pause and prev.get("recurring_amount") == a.get("recurring_amount") is not None
                c(f"{aid}.paused", ok_pause, f"confirmed immediately before by a named human seeing {kind!r} for {amt!r}")
                c(f"{aid}.not_declined", (kind, amt) not in declined, "not something the human declined")
                if kind in PAID:
                    v = _num(amt, f"{aid}.amount")
                    spent += v
                    paid.append(v)
                    c(f"{aid}.currency", v == 0 or a.get("currency") == d.get("currency"), f"{a.get('currency')!r} vs declared {d.get('currency')!r}")
                    c(f"{aid}.ceiling", spent <= ceiling + 1e-9, f"running total {spent:g}, ceiling {ceiling:g}")
                    rc = a.get("receipt") if isinstance(a.get("receipt"), dict) else {}
                    c(f"{aid}.receipt", isinstance(rc.get("id"), str) and bool(rc["id"]) and rc.get("amount") == amt,
                      f"receipt {rc.get('id')!r} for {rc.get('amount')!r}")
            elif kind not in NONCOMMIT:
                c(f"{aid}.kind", False, f"unknown action kind {kind!r}")
            last_at = at

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

        computed = {"declared_before_browsing": all_ok(lambda i: i.startswith("declaration.")),
                    "stayed_in_bounds": all_ok(lambda i: i.endswith((".site", ".deadline", ".declared_type", ".kind"))),
                    "paused_before_commit": all_ok(lambda i: i.endswith((".paused", ".not_declined"))),
                    "receipts_recorded": all_ok(lambda i: i.endswith(".receipt")),
                    "within_spend": all_ok(lambda i: i.endswith((".ceiling", ".currency")))}
        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, "actions": len(actions), "commitments": n_commit, "spent": round(spent, 2),
                        "ceiling": ceiling})
    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.errand.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-066, {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))
