"""CAIN-A75-071 offline verifier (rules embedded verbatim). CAIN-A75-071 proactive assistant lease rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

An assistant that reaches out before being asked holds a standing authority to interrupt and act. It needs a reason, a relevance
check, a quiet default and a hard limit on what it may do without a fresh instruction. Separate initiative from authority: the
agent may propose, but a standing lease defines what it may execute unattended, and the lease is reviewable and revocable. The
review recomputes every proactive event:

  lease        a named human granted the lease with topics, sources, unattended action kinds, a daily outreach limit, quiet
               hours and an expiry; every event falls inside the lease (after the grant, before expiry and before any revocation)
  relevance    every event names a lease topic and a lease source and states a reason
  quiet        no event falls in the quiet hours (local time = UTC hour + the lease's offset), and no day has more
               interruptions (notifications and proposals) than the daily limit
  authority    a proposal never executes; an act of an unattended kind may run; an act of any other kind needs a fresh grant
               from the lease holder for that kind, given after a proposal of it and before the act
  audit        the user-visible audit log is a SHA-256 chain with one entry per event, sealed by a head and count
  claims       every boolean the record asserts matches what this review computed

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND. It reviews the lease record; it does not
run an assistant or read the user's sources.
"""
from __future__ import annotations

import hashlib
import json
import math

GENESIS = "0" * 64


class Bad(ValueError):
    pass


def entry_hash(prev, entry):
    body = {k: v for k, v in entry.items() if k not in ("hash", "prev")}
    return hashlib.sha256((prev + json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=True)).encode()).hexdigest()


def chain(log):
    prev = GENESIS
    for k, e in enumerate(log, start=1):
        e["seq"] = k
        e["prev"] = prev
        e["hash"] = prev = entry_hash(prev, e)
    return prev


def _num(v, what, lo=-1e15, 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 local_hour(at, offset):
    return int(((at // 3600) + offset) % 24)


def in_quiet(hour, quiet):
    start, end = quiet
    return start <= hour < end if start <= end else (hour >= start or hour < end)


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.proactive.review.v1":
            raise Bad("not a cain42.a75.proactive.review.v1 record")
        L = record.get("lease")
        if not isinstance(L, dict):
            raise Bad("lease must be an object")
        for k in ("topics", "sources", "unattended_actions"):
            if not isinstance(L.get(k), list):
                raise Bad(f"lease.{k} must be a list")
        g0, exp = _num(L.get("granted_at"), "granted_at"), _num(L.get("expires_at"), "expires_at")
        rev = _num(L["revoked_at"], "revoked_at") if L.get("revoked_at") is not None else math.inf
        limit = int(_num(L.get("max_outreach_per_day"), "max_outreach_per_day", 0, 1000))
        quiet = L.get("quiet_hours")
        if not (isinstance(quiet, list) and len(quiet) == 2 and all(isinstance(h, int) and not isinstance(h, bool) and 0 <= h < 24 for h in quiet)):
            raise Bad("lease.quiet_hours must be [start_hour, end_hour]")
        offset = int(_num(L.get("utc_offset_hours"), "utc_offset_hours", -12, 14))
        holder = L.get("holder")
        c("lease.granted", isinstance(holder, str) and holder.startswith("human:") and exp > g0, f"granted by {holder!r} from {g0:g} to {exp:g}")
        ev = record.get("events")
        if not isinstance(ev, list) or not ev or not all(isinstance(e, dict) for e in ev):
            raise Bad("events must be a non-empty list of objects")
        per_day, proposed, n_act = {}, {}, 0
        grants = [g for g in (record.get("fresh_grants") or []) if isinstance(g, dict)]
        for k, e in enumerate(ev, start=1):
            at, kind, eid = _num(e.get("at"), f"event {k}.at"), e.get("kind"), f"event.{k}"
            c(f"{eid}.in_lease", g0 <= at < min(exp, rev), f"at {at:g}; lease {g0:g}..{min(exp, rev):g}")
            c(f"{eid}.relevant", e.get("topic") in L["topics"] and e.get("source") in L["sources"]
              and isinstance(e.get("reason"), str) and len(e["reason"].strip()) >= 8,
              f"topic {e.get('topic')!r}, source {e.get('source')!r}, reason {e.get('reason')!r}")
            h = local_hour(at, offset)
            c(f"{eid}.quiet", not in_quiet(h, quiet), f"local hour {h}, quiet hours {quiet}")
            if kind in ("notify", "propose"):
                day = int((at + offset * 3600) // 86400)
                per_day[day] = per_day.get(day, 0) + 1
            if kind == "propose":
                proposed.setdefault(e.get("action_kind"), []).append(at)
                c(f"{eid}.not_executed", e.get("executed") is not True, "a proposal does not execute")
            elif kind == "act":
                n_act += 1
                ak = e.get("action_kind")
                if ak in L["unattended_actions"]:
                    c(f"{eid}.authority", True, f"{ak!r} is an unattended action under the lease")
                else:
                    ok = any(g.get("by") == holder and g.get("action_kind") == ak and isinstance(g.get("at"), (int, float))
                             and not isinstance(g.get("at"), bool) and g["at"] < at
                             and any(p < g["at"] for p in proposed.get(ak, [])) for g in grants)
                    c(f"{eid}.authority", ok, f"{ak!r} is outside the lease and needs a fresh grant by {holder!r} after a proposal")
            elif kind != "notify":
                c(f"{eid}.kind", False, f"unknown event kind {kind!r}")
        over = sorted(d for d, n in per_day.items() if n > limit)
        c("quiet.daily_limit", not over, f"days over the limit of {limit}: {over}" if over else f"at most {limit} a day")
        log = record.get("audit_log")
        if not isinstance(log, list) or not all(isinstance(x, dict) for x in log):
            raise Bad("audit_log must be a list of objects")
        prev, ok = GENESIS, True
        for k, x in enumerate(log, start=1):
            ok &= x.get("seq") == k and x.get("prev") == prev and x.get("hash") == entry_hash(prev, x)
            prev = x.get("hash") if isinstance(x.get("hash"), str) else ""
        seal = record.get("audit_seal") if isinstance(record.get("audit_seal"), dict) else {}
        c("audit.chain", ok, "audit entries chain by SHA-256")
        c("audit.complete", len(log) == len(ev) and seal.get("head") == prev and seal.get("events") == len(log)
          and all(x.get("event_at") == e.get("at") and x.get("kind") == e.get("kind") for x, e in zip(log, ev)),
          f"{len(log)} audit entries for {len(ev)} events, sealed {seal.get('events')!r}")

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

        computed = {"within_lease": all_ok(lambda i: i == "lease.granted" or i.endswith((".in_lease", ".relevant", ".kind"))),
                    "quiet_by_default": all_ok(lambda i: i.startswith("quiet.") or i.endswith(".quiet")),
                    "fresh_grant_for_new_actions": all_ok(lambda i: i.endswith((".authority", ".not_executed"))),
                    "revocable_and_audited": all_ok(lambda i: i.startswith("audit."))}
        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, "events": len(ev), "acts": n_act, "busiest_day": max(per_day.values()) if per_day else 0,
                        "daily_limit": limit})
    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.proactive.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-071, {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))
