"""CAIN-A75-065 offline verifier (rules embedded verbatim). CAIN-A75-065 mobile work/personal data boundary rules. Standard library only, no CAIN imports: embedded verbatim in the
offline verifier.

A separation control is only real if the data path enforces it. If a mobile agent can read the work profile through a share
sheet, the clipboard, screen capture or an accessibility service, the policy is decorative. Enforce the boundary at the data and
identity layer, not only in the UI. The review recomputes a device session:

  tags         every data item carries a profile (work / personal), a handling class (public / internal / confidential) and,
               in the work profile, a tenant
  context      every context assembly for an agent task includes only items of the task's profile (and, for work, the task's
               tenant); the stated filtered-out list equals the candidates that were left out
  channels     every cross-profile channel event is re-decided: work -> personal is allowed only for a public item, through
               the share sheet, initiated by the user; personal -> work only through the share sheet or clipboard, initiated
               by the user; screen capture, accessibility and notification mirroring across profiles are always denied. The
               stated decision must equal the recomputed one
  tools        every tool call uses only items its agent's profile may read, and sends them only to a destination in the same
               profile as each item
  log          every boundary decision is recorded in a SHA-256 hash chain with contiguous sequence numbers, sealed by a
               recorded head hash and event count so a dropped last decision is detected
  claims       every boolean the session asserts matches what this review computed

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND. It reviews the session record; it does
not inspect a phone, an MDM policy or the operating system's enforcement.
"""
from __future__ import annotations

import hashlib
import json
import math
import re

_ID = re.compile(r"^[A-Za-z0-9_.:\-/@]{1,120}$")
PROFILES = ("work", "personal")
HANDLING = ("public", "internal", "confidential")
CHANNELS = ("share_sheet", "clipboard", "screen_capture", "accessibility", "notification")
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(events):
    prev = GENESIS
    for k, e in enumerate(events, start=1):
        e["seq"] = k
        e["prev"] = prev
        e["hash"] = prev = entry_hash(prev, e)
    return prev


def expected_channel(ev, item):
    src, dst, ch, user = ev.get("from_profile"), ev.get("to_profile"), ev.get("channel"), ev.get("user_initiated") is True
    if src == dst:
        return "ALLOW"
    if ch in ("screen_capture", "accessibility", "notification") or ch not in CHANNELS:
        return "DENY"
    if src == "work" and dst == "personal":
        return "ALLOW" if item is not None and item.get("handling") == "public" and ch == "share_sheet" and user else "DENY"
    if src == "personal" and dst == "work":
        return "ALLOW" if ch in ("share_sheet", "clipboard") and user else "DENY"
    return "DENY"


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 _id(v, what):
    if not isinstance(v, str) or not _ID.match(v):
        raise Bad(f"{what} must be an id")
    return v


def _ids(v, what):
    if not isinstance(v, list) or not all(isinstance(x, str) for x in v):
        raise Bad(f"{what} must be a list of ids")
    return 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.mobileboundary.review.v1":
            raise Bad("not a cain42.a75.mobileboundary.review.v1 record")
        work_tenant = _id(record.get("work_tenant"), "work_tenant")
        items = record.get("items")
        if not isinstance(items, list) or not items:
            raise Bad("items must be a non-empty list")
        I = {}
        for it in items:
            if not isinstance(it, dict):
                raise Bad("an item must be an object")
            iid = _id(it.get("id"), "item.id")
            if iid in I:
                raise Bad(f"duplicate item {iid}")
            I[iid] = it
            c(f"item.{iid}.tagged", it.get("profile") in PROFILES and it.get("handling") in HANDLING
              and (it.get("profile") != "work" or it.get("tenant") == work_tenant),
              f"profile {it.get('profile')!r}, handling {it.get('handling')!r}, tenant {it.get('tenant')!r}")

        def readable(item, profile, tenant=None):
            return item is not None and item.get("profile") == profile and (profile != "work" or item.get("tenant") == (tenant or work_tenant))

        agents = {}
        for a in record.get("agents") or []:
            if isinstance(a, dict):
                agents[_id(a.get("id"), "agent.id")] = a
        if not agents:
            raise Bad("agents must be non-empty")
        for a in agents.values():
            if a.get("profile") not in PROFILES:
                raise Bad(f"agent {a.get('id')} needs a profile")

        n_ctx = 0
        for k, ctx in enumerate(record.get("contexts") or [], start=1):
            if not isinstance(ctx, dict):
                raise Bad("a context must be an object")
            n_ctx += 1
            ag = agents.get(ctx.get("agent"))
            prof = ag.get("profile") if ag else None
            cand, inc, out = _ids(ctx.get("candidates"), "candidates"), _ids(ctx.get("included"), "included"), _ids(ctx.get("filtered_out"), "filtered_out")
            leaked = [x for x in inc if not readable(I.get(x), prof, ctx.get("tenant"))]
            c(f"context.{k}.filtered", ag is not None and not leaked and set(inc) <= set(cand),
              f"included items outside the {prof!r} boundary: {leaked}" if leaked else f"only {prof!r} items included")
            c(f"context.{k}.filter_recorded", sorted(out) == sorted(set(cand) - set(inc)),
              f"stated filtered {sorted(out)}, recomputed {sorted(set(cand) - set(inc))}")

        events = record.get("boundary_log")
        if not isinstance(events, list) or not events:
            raise Bad("boundary_log must be a non-empty list")
        prev, chain_ok, seq_ok, crossings, denied = GENESIS, True, True, 0, 0
        for k, ev in enumerate(events, start=1):
            if not isinstance(ev, dict):
                raise Bad("a boundary event must be an object")
            _num(ev.get("at"), f"event {k}.at")
            seq_ok &= ev.get("seq") == k
            chain_ok &= ev.get("prev") == prev and ev.get("hash") == entry_hash(prev, ev)
            prev = ev.get("hash") if isinstance(ev.get("hash"), str) else ""
            if ev.get("type") == "channel":
                item = I.get(ev.get("item"))
                c(f"event.{k}.item", item is not None and item.get("profile") == ev.get("from_profile"),
                  f"item {ev.get('item')!r} belongs to the source profile {ev.get('from_profile')!r}")
                exp = expected_channel(ev, item)
                crossings += ev.get("from_profile") != ev.get("to_profile")
                denied += exp == "DENY"
                c(f"event.{k}.decision", ev.get("decision") == exp,
                  f"{ev.get('channel')!r} {ev.get('from_profile')!r}->{ev.get('to_profile')!r}: stated {ev.get('decision')!r}, recomputed {exp!r}")
            elif ev.get("type") == "tool_call":
                ag = agents.get(ev.get("agent"))
                used = _ids(ev.get("items"), f"event {k}.items")
                bad_read = [x for x in used if ag is None or not readable(I.get(x), ag.get("profile"))]
                bad_dest = [x for x in used if I.get(x) is not None and I[x].get("profile") != ev.get("destination_profile")]
                ok = not bad_read and not bad_dest
                c(f"event.{k}.tool", ok and ev.get("decision") == "ALLOW" or (not ok and ev.get("decision") == "DENY"),
                  f"tool {ev.get('tool')!r}: unreadable {bad_read}, wrong destination {bad_dest}, stated {ev.get('decision')!r}")
            else:
                c(f"event.{k}.type", False, f"unknown event type {ev.get('type')!r}")
        c("log.chain", chain_ok, "every boundary decision chains by SHA-256")
        c("log.contiguous", seq_ok, "sequence numbers 1..n")
        seal = record.get("log_seal") if isinstance(record.get("log_seal"), dict) else {}
        c("log.sealed", seal.get("head") == prev and seal.get("events") == len(events),
          f"sealed head {str(seal.get('head'))[:12]} / {seal.get('events')!r} events vs recomputed {prev[:12]} / {len(events)} (truncation)")

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

        computed = {"items_tagged": all_ok(lambda i: i.startswith("item.")),
                    "context_filtered_by_tag": all_ok(lambda i: i.startswith("context.")),
                    "cross_boundary_blocked": all_ok(lambda i: i.endswith((".decision", ".item"))),
                    "tool_calls_checked": all_ok(lambda i: i.endswith((".tool", ".type"))),
                    "decisions_recorded": all_ok(lambda i: i.startswith("log."))}
        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, "items": len(I), "contexts": n_ctx, "events": len(events),
                        "crossings": crossings, "denied": denied})
    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.mobileboundary.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-065, {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))
