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

Persistent memory that learns from corrections is useful and dangerous: a remembered sentence can outlive the fact it described,
cross a tenant boundary, or be treated as an instruction. The review recomputes a memory store and its retrievals:

  provenance    every memory names its author, its source (reference and SHA-256), a content SHA-256, a tenant and the purposes
                it may be used for
  screened      every memory was screened at write time, by a screener that is not its author, before its first retrieval
  supersession  a correction supersedes exactly one older memory in the same tenant; a memory has at most one successor and the
                chain cannot loop
  retrieval     a retrieval returns only memories of its own tenant, allowed for its purpose, and current at that moment: not
                superseded, not revoked, not quarantined
  no authority  a retrieved memory is used as context only; an action taken after a retrieval cites a grant from a named human,
                never a memory
  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 record of the store; it
does not read the store itself and does not judge whether a remembered statement is true.
"""
from __future__ import annotations

import math
import re

_HEX = re.compile(r"^[0-9a-f]{64}$")
SCHEMA = "cain42.a75.memoryauthority.review.v1"
KINDS = ("fact", "preference", "correction")
MAX_ITEMS = 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 _hex(v):
    return isinstance(v, str) and bool(_HEX.match(v))


def _who(v, kinds):
    return isinstance(v, str) and v.split(":", 1)[0] in kinds and len(v.split(":", 1)) == 2 and bool(v.split(":", 1)[1])


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")
        mems, rets, grants = record.get("memories"), record.get("retrievals"), record.get("grants")
        if not isinstance(mems, list) or not mems or not isinstance(rets, list) or not isinstance(grants, dict) \
                or len(mems) > MAX_ITEMS or len(rets) > MAX_ITEMS:
            raise Bad(f"memories (1 to {MAX_ITEMS}), retrievals (at most {MAX_ITEMS}) and grants are required")
        by_id = {}
        for m in mems:
            if not isinstance(m, dict) or not isinstance(m.get("id"), str) or not m["id"]:
                raise Bad("a memory needs an id")
            if m["id"] in by_id:
                raise Bad(f"memory id {m['id']!r} is used twice")
            m_at = _num(m.get("created_at"), f"{m['id']}.created_at")
            if m.get("revoked_at") is not None:
                _num(m["revoked_at"], f"{m['id']}.revoked_at")
            by_id[m["id"]] = m
        first_use = {}
        for r in rets:
            if not isinstance(r, dict) or not isinstance(r.get("id"), str) or not isinstance(r.get("returned"), list):
                raise Bad("a retrieval needs an id and a returned list")
            at = _num(r.get("at"), f"{r['id']}.at")
            for mid in r["returned"]:
                if isinstance(mid, str):
                    first_use[mid] = min(first_use.get(mid, at), at)
        successor, forks = {}, set()
        for m in mems:
            s = m.get("supersedes")
            if s is not None:
                if s in successor:
                    forks.add(s)
                successor.setdefault(s, m["id"])
        for m in mems:
            mid, k = m["id"], f"memory.{m['id']}"
            src = m.get("source") if isinstance(m.get("source"), dict) else {}
            scope = m.get("purposes")
            c(f"{k}.provenance", _who(m.get("author"), ("human", "agent", "tool")) and isinstance(src.get("ref"), str) and bool(src.get("ref"))
              and _hex(src.get("sha256")) and _hex(m.get("content_sha256")) and isinstance(m.get("tenant"), str) and bool(m.get("tenant"))
              and isinstance(scope, list) and bool(scope) and all(isinstance(x, str) and x for x in scope) and m.get("kind") in KINDS,
              f"author {m.get('author')!r}, source {src.get('ref')!r}, tenant {m.get('tenant')!r}, kind {m.get('kind')!r}")
            sc = m.get("screening") if isinstance(m.get("screening"), dict) else {}
            s_at = sc.get("at")
            ok_sc = isinstance(s_at, (int, float)) and not isinstance(s_at, bool) and s_at >= m["created_at"] \
                and sc.get("result") in ("clean", "quarantined") and _who(sc.get("screener"), ("human", "tool")) and sc.get("screener") != m.get("author") \
                and (mid not in first_use or s_at <= first_use[mid])
            c(f"{k}.screened", ok_sc, f"screened {sc.get('result')!r} at {s_at!r} by {sc.get('screener')!r}; first retrieved at {first_use.get(mid)!r}")
            s = m.get("supersedes")
            if m.get("kind") == "correction" or s is not None:
                old = by_id.get(s)
                seen, cur, loop = {mid}, s, False
                while cur is not None and cur in by_id:
                    if cur in seen:
                        loop = True
                        break
                    seen.add(cur)
                    cur = by_id[cur].get("supersedes")
                c(f"{k}.supersession", old is not None and s != mid and not loop and old.get("tenant") == m.get("tenant")
                  and old["created_at"] < m["created_at"] and s not in forks,
                  f"supersedes {s!r}" + ("" if old is not None else " (not in the store)") + (" in a loop" if loop else "")
                  + (" which has more than one successor" if s in forks else ""))

        def state_at(m, at):
            if (m.get("screening") or {}).get("result") == "quarantined":
                return "quarantined"
            if m.get("revoked_at") is not None and m["revoked_at"] <= at:
                return "revoked"
            nxt = by_id.get(successor.get(m["id"]))
            if nxt is not None and nxt["created_at"] <= at:
                return "superseded"
            return "current"

        for r in rets:
            k, at = f"retrieval.{r['id']}", float(r["at"])
            got = [by_id.get(x) if isinstance(x, str) else None for x in r["returned"]]
            unknown = [str(x) for x, m in zip(r["returned"], got) if m is None]
            got = [m for m in got if m is not None]
            foreign = sorted(m["id"] for m in got if m.get("tenant") != r.get("tenant"))
            c(f"{k}.tenant", not unknown and not foreign and isinstance(r.get("tenant"), str),
              f"unknown {unknown}, other-tenant {foreign}" if (unknown or foreign) else f"{len(got)} memories, all in {r.get('tenant')!r}")
            off = sorted(m["id"] for m in got if r.get("purpose") not in (m.get("purposes") if isinstance(m.get("purposes"), list) else []))
            c(f"{k}.purpose", not off, f"not allowed for purpose {r.get('purpose')!r}: {off}" if off else f"purpose {r.get('purpose')!r} allowed")
            stale = sorted(f"{m['id']} ({state_at(m, at)})" for m in got if state_at(m, at) != "current" or m["created_at"] > at)
            c(f"{k}.current", not stale, f"not current at {at}: {stale}" if stale else "every returned memory was current")
            act = r.get("action")
            g = grants.get(act.get("authority")) if isinstance(act, dict) and isinstance(act.get("authority"), str) else None
            ok_auth = r.get("used_as") == "context" and (act is None or (
                isinstance(act, dict) and act.get("authority") not in by_id and isinstance(g, dict) and _who(g.get("by"), ("human",))
                and act.get("op") in (g.get("ops") if isinstance(g.get("ops"), list) else []) and g.get("tenant") == r.get("tenant")
                and isinstance(g.get("expires_at"), (int, float)) and not isinstance(g.get("expires_at"), bool) and at <= g["expires_at"]))
            c(f"{k}.no_authority", ok_auth, f"used as {r.get('used_as')!r}" + ("" if act is None else
              f"; action {act.get('op')!r} cites {act.get('authority')!r}" if isinstance(act, dict) else "; malformed action"))

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

        computed = {"provenance_complete": all_ok(lambda i: i.endswith(".provenance")),
                    "screened_at_write": all_ok(lambda i: i.endswith(".screened")),
                    "corrections_supersede": all_ok(lambda i: i.endswith(".supersession")),
                    "retrievals_scoped_and_current": all_ok(lambda i: i.endswith((".tenant", ".purpose", ".current"))),
                    "memory_never_authority": all_ok(lambda i: i.endswith(".no_authority"))}
        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}")
        end = max([m["created_at"] for m in mems] + [float(r["at"]) for r in rets])
        states = [state_at(m, end) for m in mems]
        summary.update({"computed": computed, "memories": len(mems), "current": states.count("current"), "superseded": states.count("superseded"),
                        "revoked": states.count("revoked"), "quarantined": states.count("quarantined"), "retrievals": len(rets),
                        "tenants": len({m.get("tenant") for m in mems if isinstance(m.get("tenant"), str)})})
    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.memoryauthority.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-014, {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))
