"""CAIN-A75-030 offline verifier (rules embedded verbatim). CAIN-A75-030/040/060 tool-boundary rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

An agent reaches a system through tools. The boundary decides every call; the review recomputes those decisions from the
declared policy, call by call:

  boundary   a named human operator, tenant, agent, an exact allowlist, and a policy: deny shell, allowed hosts, allowed
             paths, a call limit, and the tools that need a human approval
  decision   for each call in time order: tool must be allowed, shell must be denied when the policy says so, network calls
             must target an allowed host, file calls must stay under an allowed path, approval-gated tools need a named human
             other than the agent, and calls past the limit are denied
  execution  an ALLOW is executed and a DENY is not; a denied call that ran is the failure this review exists to catch
  claims     every boolean the record asserts matches what this review computed
  summary    published allowed / denied / executed counts equal the recomputation

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND. It reviews the call log; it does not
call any tool and cannot see a call that was never logged.
"""
from __future__ import annotations

import math
import re
from urllib.parse import urlparse

SCHEMA = "cain42.a75.toolboundary.review.v1"
SHELL = {"run_shell", "shell", "exec", "bash", "terminal", "run_command"}
MAX_CALLS = 10000


class Bad(ValueError):
    pass


def _who(v, kinds=("human", "agent", "tool", "org")):
    return isinstance(v, str) and ":" in v and v.split(":", 1)[0] in kinds and bool(v.split(":", 1)[1])


def _num(v):
    return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)


def host_ok(patterns, host):
    if not isinstance(host, str) or not host:
        return False
    for p in patterns or []:
        if not isinstance(p, str):
            continue
        if p.startswith("*."):
            if host.endswith(p[1:]) and len(host) > len(p) - 1:
                return True
        elif host == p:
            return True
    return False


def path_ok(prefixes, path):
    if not isinstance(path, str) or not path.startswith("/"):
        return False
    for p in prefixes or []:
        if isinstance(p, str) and (path == p.rstrip("/") or path.startswith(p if p.endswith("/") else p + "/")):
            return True
    return False


def decide(call, policy, allowed_tools, index):
    tool = call.get("tool")
    if tool not in allowed_tools:
        return "DENY", "unknown_tool"
    if policy.get("deny_shell") is True and tool in SHELL:
        return "DENY", "blocked_tool"
    if tool in (policy.get("require_human_for") or []):
        if not (_who(call.get("approved_by"), ("human",)) and call.get("approved_by") != call.get("agent")):
            return "DENY", "approval_required"
    args = call.get("args")
    if not isinstance(args, dict):
        return "DENY", "bad_arguments"
    host = args.get("host")
    if host is None and isinstance(args.get("url"), str):
        try:
            host = urlparse(args["url"]).hostname
        except ValueError:
            host = None
    if host is not None and not host_ok(policy.get("allowed_hosts"), host):
        return "DENY", "host_not_allowed"
    if "path" in args and not path_ok(policy.get("allowed_paths"), args.get("path")):
        return "DENY", "path_not_allowed"
    cap = policy.get("max_calls")
    if isinstance(cap, int) and not isinstance(cap, bool) and index >= cap:
        return "DENY", "call_limit"
    return "ALLOW", None


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")
        b, calls, pub = record.get("boundary"), record.get("calls"), record.get("published")
        if not isinstance(b, dict) or not isinstance(calls, list) or not calls or len(calls) > MAX_CALLS:
            raise Bad(f"boundary and 1 to {MAX_CALLS} calls are required")
        pol = b.get("policy") if isinstance(b.get("policy"), dict) else {}
        allowed = b.get("allowed_tools")
        c("boundary.operator", _who(b.get("operator"), ("human",)), f"operator {b.get('operator')!r}")
        c("boundary.tenant", isinstance(b.get("tenant"), str) and bool(b.get("tenant")), f"tenant {b.get('tenant')!r}")
        c("boundary.agent", _who(b.get("agent"), ("agent",)), f"agent {b.get('agent')!r}")
        c("boundary.allowlist", isinstance(allowed, list) and bool(allowed)
          and all(isinstance(x, str) and x for x in allowed), f"allowlist {allowed!r}")
        c("policy.deny_shell", pol.get("deny_shell") is True, f"deny_shell {pol.get('deny_shell')!r}")
        c("policy.hosts", isinstance(pol.get("allowed_hosts"), list), f"allowed_hosts {pol.get('allowed_hosts')!r}")
        c("policy.paths", isinstance(pol.get("allowed_paths"), list), f"allowed_paths {pol.get('allowed_paths')!r}")
        c("policy.call_limit", isinstance(pol.get("max_calls"), int) and not isinstance(pol.get("max_calls"), bool)
          and pol["max_calls"] > 0, f"max_calls {pol.get('max_calls')!r}")
        c("policy.approval_gates", isinstance(pol.get("require_human_for"), list),
          f"require_human_for {pol.get('require_human_for')!r}")

        allowed_tools = allowed if isinstance(allowed, list) else []
        executed = allowed_n = denied_n = 0
        last_at = None
        for i, call in enumerate(calls):
            if not isinstance(call, dict) or not isinstance(call.get("id"), str) or not call["id"]:
                raise Bad(f"call {i} needs an id")
            k = f"call.{call['id']}"
            c(f"{k}.time", _num(call.get("at")) and (last_at is None or call["at"] >= last_at),
              f"at {call.get('at')!r}" + (f", previous {last_at!r}" if last_at is not None else ""))
            if _num(call.get("at")):
                last_at = call["at"]
            if not _who(call.get("agent"), ("agent",)):
                c(f"{k}.agent", False, f"agent {call.get('agent')!r}")
            else:
                c(f"{k}.agent", call.get("agent") == b.get("agent"), f"agent {call.get('agent')!r}")
            decision, reason = decide(call, pol, allowed_tools, i)
            c(f"{k}.decision", call.get("decision") == decision,
              f"recorded {call.get('decision')!r}, recomputed {decision!r}")
            c(f"{k}.reason", (call.get("reason") or None) == reason,
              f"recorded {call.get('reason')!r}, recomputed {reason!r}")
            c(f"{k}.executed", call.get("executed") is (decision == "ALLOW"),
              f"executed {call.get('executed')!r}, decision {decision!r}")
            if decision == "ALLOW":
                allowed_n += 1
                executed += 1 if call.get("executed") is True else 0
            else:
                denied_n += 1

        c("published.allowed", isinstance(pub, dict) and pub.get("allowed") == allowed_n
          and not isinstance(pub.get("allowed"), bool), f"stated {pub.get('allowed') if isinstance(pub, dict) else None!r}, recomputed {allowed_n}")
        c("published.denied", isinstance(pub, dict) and pub.get("denied") == denied_n
          and not isinstance(pub.get("denied"), bool), f"stated {pub.get('denied') if isinstance(pub, dict) else None!r}, recomputed {denied_n}")
        c("published.executed", isinstance(pub, dict) and pub.get("executed") == executed
          and not isinstance(pub.get("executed"), bool), f"stated {pub.get('executed') if isinstance(pub, dict) else None!r}, recomputed {executed}")

        computed = {"every_decision_correct": all(x["ok"] for x in checks if x["id"].endswith((".decision", ".reason", ".agent", ".time"))),
                    "no_denied_call_executed": all(x["ok"] for x in checks if x["id"].endswith(".executed")),
                    "counts_match": all(x["ok"] for x in checks if x["id"].startswith("published."))}
        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, "calls": len(calls), "allowed": allowed_n, "denied": denied_n,
                        "executed": executed, "boundary": b.get("name")})
    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


def generic_refusal_cases(base):
    cases = [("honest_boundary_log", copy(base), "SOUND")]

    def mut(name, fn, expect="UNSOUND"):
        r = copy(base); fn(r); cases.append((name, r, expect))

    C = lambda r: r["calls"]  # noqa: E731
    mut("denied_call_that_ran", lambda r: C(r)[-1].__setitem__("executed", True))
    mut("allowed_call_marked_denied", lambda r: C(r)[0].__setitem__("decision", "DENY"))
    mut("wrong_deny_reason", lambda r: C(r)[-1].__setitem__("reason", "unknown_tool"))
    mut("shell_executed_by_another_agent", lambda r: C(r)[-1].__setitem__("agent", "agent:intruder"))
    mut("counts_understate_denials", lambda r: r["published"].__setitem__("denied", 0))
    mut("unknown_tool_allowed", lambda r: (C(r)[0].update(tool="not_in_allowlist", decision="ALLOW", reason=None, executed=True)))
    mut("call_after_the_limit", lambda r: r["boundary"]["policy"].__setitem__("max_calls", 1))
    mut("operator_is_an_agent", lambda r: r["boundary"].__setitem__("operator", "agent:runtime"))
    mut("unknown_claim", lambda r: r["claims"].__setitem__("all_tools_safe", True))
    mut("wrong_schema", lambda r: r.__setitem__("schema", "x"))
    cases.append(("garbage", None, "UNSOUND"))
    return cases


def copy(o):
    import copy as _c
    return _c.deepcopy(o)


# ---------------------------------------------------------------------------- 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.bizconnector.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-030, {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))
