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

Advertising agents move real budgets across many counterparties. The risk is not one bad buy; it is a sequence of small,
individually defensible buys that breaches the campaign's authority. Aggregate spend and placement authority across the
campaign, not per call. The review recomputes every buy in order, across all agents:

  authority    the campaign was issued by a named human with a total budget, currency, daily cap, per-buy ceiling, a
               counterparty allowlist, blocked categories, a validity window and the enrolled buyer agents
  buys         each buy is re-decided with the campaign-wide state: ALLOW only when the agent is enrolled, the buy is inside
               the window and in the campaign currency, the publisher is on the allowlist, the category is not blocked, the
               amount is within the per-buy ceiling, the same publisher's allowed spend in the preceding 60 seconds plus this
               buy stays within the per-buy ceiling (a split buy across calls or agents), the day's allowed spend stays within
               the daily cap, the campaign total stays within the budget, and the campaign is not paused. The stated decision
               must equal the recomputed one
  control      when allowed spend first reaches 90% of the budget an "approaching" alert is recorded before the next buy;
               when a buy is refused for the budget a pause is recorded before the next buy, and nothing is allowed after it
  report       the reported total and per-publisher spend equal the recomputation
  claims       every boolean the campaign record asserts matches what this review computed

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND. It reviews the campaign record; it
does not bid, connect to an ad exchange or verify an impression.
"""
from __future__ import annotations

import math
import re

_ID = re.compile(r"^[A-Za-z0-9_.:\-/@]{1,120}$")
SPLIT_WINDOW = 60.0
DAY = 86400.0
ALERT_AT = 0.9


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 _times(v, what):
    if not isinstance(v, list) or not all(isinstance(x, dict) for x in v):
        raise Bad(f"{what} must be a list of objects")
    return sorted(_num(x.get("at"), f"{what}.at") for x in v)


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.campaign.review.v1":
            raise Bad("not a cain42.a75.campaign.review.v1 record")
        a = record.get("authority")
        if not isinstance(a, dict):
            raise Bad("authority must be an object")
        budget, daily, per_buy = _num(a.get("budget"), "budget"), _num(a.get("daily_cap"), "daily_cap"), _num(a.get("per_buy_ceiling"), "per_buy_ceiling")
        v0, v1 = _num(a.get("valid_from"), "valid_from"), _num(a.get("valid_to"), "valid_to")
        pubs, blocked, agents = a.get("publishers"), a.get("blocked_categories"), a.get("agents")
        if not all(isinstance(x, list) for x in (pubs, blocked, agents)) or not pubs or not agents:
            raise Bad("authority needs publishers, blocked_categories and agents lists")
        c("authority.issued", isinstance(a.get("issued_by"), str) and a["issued_by"].startswith("human:") and v1 > v0
          and per_buy <= daily <= budget, f"issued by {a.get('issued_by')!r}; per-buy {per_buy:g} <= daily {daily:g} <= budget {budget:g}")

        alerts, pauses = _times(record.get("alerts", []), "alerts"), _times(record.get("pauses", []), "pauses")
        buys = record.get("buys")
        if not isinstance(buys, list) or not buys or not all(isinstance(b, dict) for b in buys):
            raise Bad("buys must be a non-empty list of objects")
        total, by_day, recent, by_pub, last, expected = 0.0, {}, [], {}, -1.0, []
        need_alert_after, need_pause_after, n_allow, n_deny = None, None, 0, 0
        times = [_num(b.get("at"), "buy.at") for b in buys]
        if times != sorted(times):
            raise Bad("buys must be in time order")
        for k, b in enumerate(buys, start=1):
            at, amt, pub = times[k - 1], _num(b.get("amount"), f"buy {k}.amount"), b.get("publisher")
            nxt = times[k] if k < len(times) else math.inf
            paused = any(p <= at for p in pauses)
            day = int((at - v0) // DAY)
            win = sum(x for t, p, x in recent if p == pub and at - t <= SPLIT_WINDOW)
            why = []
            if b.get("agent") not in agents:
                why.append("agent not enrolled")
            if not (v0 <= at < v1):
                why.append("outside the window")
            if b.get("currency") != a.get("currency"):
                why.append("currency")
            if pub not in pubs:
                why.append("publisher not on allowlist")
            if b.get("category") in blocked:
                why.append("blocked category")
            if amt > per_buy:
                why.append("over per-buy ceiling")
            if paused:
                why.append("campaign paused")
            if not why and win + amt > per_buy + 1e-9:
                why.append(f"split buy ({win:g} to {pub} in the last {SPLIT_WINDOW:g}s)")
            if not why and by_day.get(day, 0.0) + amt > daily + 1e-9:
                why.append("daily cap")
            budget_refusal = not why and total + amt > budget + 1e-9
            if budget_refusal:
                why.append("budget exhausted")
            exp = "DENY" if why else "ALLOW"
            expected.append(exp)
            c(f"buy.{k}.decision", b.get("decision") == exp,
              f"{b.get('agent')!r} {amt:g} to {pub!r}: stated {b.get('decision')!r}, recomputed {exp!r}" + (f" ({', '.join(why)})" if why else ""))
            if budget_refusal and need_pause_after is None:
                need_pause_after = (at, nxt)
            if exp == "ALLOW" and b.get("decision") == "ALLOW":
                n_allow += 1
                before = total
                total += amt
                by_day[day] = by_day.get(day, 0.0) + amt
                by_pub[pub] = by_pub.get(pub, 0.0) + amt
                recent.append((at, pub, amt))
                if before < ALERT_AT * budget <= total and need_alert_after is None:
                    need_alert_after = (at, nxt)
            else:
                n_deny += 1
            last = at
        if need_alert_after:
            lo, hi = need_alert_after
            c("control.alert", any(lo <= t <= hi for t in alerts), f"an 'approaching' alert between {lo:g} and the next buy")
        else:
            c("control.alert", True, f"allowed spend never reached {ALERT_AT:.0%} of the budget")
        if need_pause_after:
            lo, hi = need_pause_after
            c("control.pause", any(lo <= t <= hi for t in pauses), f"a pause between the budget refusal at {lo:g} and the next buy")
        rep = record.get("report") if isinstance(record.get("report"), dict) else {}
        rp = rep.get("by_publisher") if isinstance(rep.get("by_publisher"), dict) else {}
        want = {k: round(by_pub[k], 2) for k in sorted(by_pub)}
        got = {str(k): round(rp[k], 2) for k in sorted(rp, key=str) if isinstance(rp[k], (int, float)) and not isinstance(rp[k], bool)}
        c("report.total", isinstance(rep.get("total"), (int, float)) and abs(rep["total"] - total) <= 0.005,
          f"reported {rep.get('total')!r}, recomputed {round(total, 2)}")
        c("report.by_publisher", got == want, f"reported {got}, recomputed {want}")

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

        computed = {"aggregate_enforced": all_ok(lambda i: i.endswith(".decision") or i == "authority.issued"),
                    "paused_when_exhausted": all_ok(lambda i: i.startswith("control.")),
                    "spend_reported": all_ok(lambda i: i.startswith("report."))}
        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, "buys": len(buys), "allowed": n_allow, "denied": n_deny,
                        "spent": round(total, 2), "budget": budget, "by_publisher": want, "expected": expected,
                        "alert_due": need_alert_after[0] if need_alert_after else None,
                        "pause_due": need_pause_after[0] if need_pause_after else None})
    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.campaign.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-067, {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))
