"""CAIN-A75-021 offline verifier (rules embedded verbatim). CAIN-A75-021 agent credential rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

A standing API key in an agent's hands is authority with no task, no lifetime and no memory of use. A task-scoped credential is
the opposite: one subject, one task, one action on one resource with one parameter digest, a short life and a single use. The
review recomputes a broker's issuance and use log:

  bound        every credential is ephemeral, issued by the broker (never by the agent), to the agent assigned to a task that a
               named human owns, for one action, one resource and one SHA-256 parameter digest, with a unique nonce
  task open    the task was open when the credential was issued
  short life   the lifetime is positive and no longer than the policy maximum
  each use     the outcome of every use is recomputed in time order: the presenter, action, resource, parameter digest and nonce
               must match, the credential must be inside its lifetime, not revoked, its task still open, and a single-use
               credential must not have been accepted before. The recorded outcome and refusal reason must equal the recomputed one
  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 log; it does not contact
the broker and cannot see a use that was never logged.
"""
from __future__ import annotations

import math
import re

_HEX = re.compile(r"^[0-9a-f]{64}$")
SCHEMA = "cain42.a75.credentialreview.review.v1"
MAX_ITEMS = 5000


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 _pre(v, prefix):
    return isinstance(v, str) and v.startswith(prefix) and len(v) > len(prefix)


def expected_outcome(use, cred, task, accepted_before):
    """(result, reason) the broker must give this use. Order of the tests is the order a broker should apply them."""
    if cred is None:
        return "refused", "unknown_credential"
    at = use["at"]
    if cred.get("revoked_at") is not None and cred["revoked_at"] <= at:
        return "refused", "revoked"
    if at < cred["issued_at"] or at > cred["expires_at"]:
        return "refused", "expired"
    if task is None or (task.get("closed_at") is not None and task["closed_at"] <= at):
        return "refused", "task_closed"
    if use.get("by") != cred.get("subject"):
        return "refused", "wrong_subject"
    if use.get("nonce") != cred.get("nonce"):
        return "refused", "wrong_nonce"
    if (use.get("action"), use.get("resource")) != (cred.get("action"), cred.get("resource")):
        return "refused", "scope_mismatch"
    if use.get("param_sha256") != cred.get("param_sha256"):
        return "refused", "parameters_changed"
    if cred.get("single_use") is not False and accepted_before:
        return "refused", "replay"
    return "accepted", 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")
        pol, tasks, creds, uses = record.get("policy"), record.get("tasks"), record.get("credentials"), record.get("uses")
        if not isinstance(pol, dict) or not isinstance(tasks, dict) or not isinstance(creds, list) or not creds or not isinstance(uses, list) \
                or len(creds) > MAX_ITEMS or len(uses) > MAX_ITEMS:
            raise Bad(f"policy, tasks, credentials (1 to {MAX_ITEMS}) and uses (at most {MAX_ITEMS}) are required")
        max_ttl = _num(pol.get("max_ttl_seconds"), "policy.max_ttl_seconds")
        if max_ttl <= 0 or not _pre(pol.get("broker"), "service:"):
            raise Bad("policy needs a positive max_ttl_seconds and a broker named service:...")
        for tid, t in tasks.items():
            if not isinstance(t, dict):
                raise Bad(f"task {tid!r} must be an object")
            _num(t.get("opened_at"), f"{tid}.opened_at")
            if t.get("closed_at") is not None:
                _num(t["closed_at"], f"{tid}.closed_at")
        by_id, nonces, longest = {}, {}, 0.0
        for cr in creds:
            if not isinstance(cr, dict) or not isinstance(cr.get("id"), str) or not cr["id"]:
                raise Bad("a credential needs an id")
            if cr["id"] in by_id:
                raise Bad(f"credential id {cr['id']!r} is used twice")
            issued, expires = _num(cr.get("issued_at"), f"{cr['id']}.issued_at"), _num(cr.get("expires_at"), f"{cr['id']}.expires_at")
            if cr.get("revoked_at") is not None:
                _num(cr["revoked_at"], f"{cr['id']}.revoked_at")
            by_id[cr["id"]] = cr
            nonces.setdefault(cr.get("nonce") if isinstance(cr.get("nonce"), str) else None, []).append(cr["id"])
        for cr in creds:
            k, t = f"credential.{cr['id']}", tasks.get(cr.get("task")) if isinstance(cr.get("task"), str) else None
            ttl = cr["expires_at"] - cr["issued_at"]
            longest = max(longest, ttl)
            c(f"{k}.bound", cr.get("kind") == "ephemeral" and _pre(cr.get("subject"), "agent:") and cr.get("issued_by") == pol["broker"]
              and isinstance(cr.get("action"), str) and bool(cr.get("action")) and isinstance(cr.get("resource"), str) and bool(cr.get("resource"))
              and bool(_HEX.match(str(cr.get("param_sha256")))) and isinstance(cr.get("nonce"), str) and len(cr["nonce"]) >= 16
              and len(nonces.get(cr["nonce"], [])) == 1 and cr.get("single_use") is True and t is not None and t.get("agent") == cr.get("subject"),
              f"{cr.get('kind')!r} for {cr.get('subject')!r} on task {cr.get('task')!r}: {cr.get('action')!r} {cr.get('resource')!r}, issued by {cr.get('issued_by')!r}")
            c(f"{k}.task_open", t is not None and _pre(t.get("owner"), "human:") and t["opened_at"] <= cr["issued_at"]
              and (t.get("closed_at") is None or cr["issued_at"] < t["closed_at"]),
              "task not found" if t is None else f"task owner {t.get('owner')!r}, open {t['opened_at']}..{t.get('closed_at')!r}, issued {cr['issued_at']}")
            c(f"{k}.short_life", 0 < ttl <= max_ttl, f"lifetime {round(ttl, 3)} s, policy maximum {max_ttl} s")
        order, seen_ids = [], set()
        for u in uses:
            if not isinstance(u, dict) or not isinstance(u.get("id"), str) or u["id"] in seen_ids:
                raise Bad("every use needs a unique id")
            seen_ids.add(u["id"])
            _num(u.get("at"), f"{u['id']}.at")
            order.append(u)
        c("uses.time_ordered", all(order[i]["at"] <= order[i + 1]["at"] for i in range(len(order) - 1)), f"{len(order)} uses")
        accepted, tally = set(), {}
        for u in sorted(order, key=lambda x: x["at"]):
            cr = by_id.get(u.get("credential")) if isinstance(u.get("credential"), str) else None
            t = tasks.get(cr.get("task")) if cr is not None and isinstance(cr.get("task"), str) else None
            want, why = expected_outcome(u, cr, t, cr is not None and cr["id"] in accepted)
            got = (u.get("result"), u.get("reason") if u.get("result") == "refused" else None)
            c(f"use.{u['id']}.outcome", got == (want, why),
              f"recorded {u.get('result')!r}" + (f" ({u.get('reason')!r})" if u.get("result") == "refused" else "")
              + f", recomputed {want!r}" + (f" ({why!r})" if why else ""))
            if want == "accepted":
                accepted.add(cr["id"])
            tally[why or "accepted"] = tally.get(why or "accepted", 0) + 1

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

        computed = {"credentials_task_bound": all_ok(lambda i: i.endswith((".bound", ".task_open"))),
                    "lifetimes_within_policy": all_ok(lambda i: i.endswith(".short_life")),
                    "every_use_decided_correctly": all_ok(lambda i: i.startswith(("use.", "uses.")))}
        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, "credentials": len(creds), "uses": len(order), "accepted": tally.get("accepted", 0),
                        "refused": len(order) - tally.get("accepted", 0),
                        "refusal_reasons": {k: tally[k] for k in sorted(tally) if k != "accepted"},
                        "longest_lifetime_seconds": round(longest, 3), "never_used": len(creds) - len(accepted)})
    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.credentialreview.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-021, {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))
