"""CAIN-A75-001 offline verifier (rules embedded verbatim). CAIN-A75-001 long-run engineering attestation rules. Standard library only, no CAIN imports: embedded verbatim in
the offline verifier.

A long autonomous engineering run is many tool calls, many hours and one final claim that "it works". The review re-checks
the run record:

  authority    every action names a grant, an issuer, a subject equal to the actor, a scope that covers tool:resource and an
               expiry that had not passed when the action ran
  chain        action sequence numbers are 1..n and each action's SHA-256 link covers the previous one
  decisions    an ALLOW action was executed; a DENY or REQUIRE_APPROVAL action was not
  proof        at least one test was authored by someone other than the agent, failed on the original and passed on the fix
  artifacts    every artifact has a safe relative path and a SHA-256; every timestamp is inside the run

Verdict: VERIFIED_RUN, else NOT_VERIFIED with every failing check named. Malformed input is NOT_VERIFIED. It binds the record,
not the world: it does not prove the tests are good, the code is correct or the log is complete.
"""
from __future__ import annotations

import hashlib
import json
import re
from typing import Any, Dict, List, Tuple

SCHEMA = "cain42.a75.longrun.run.v1"
MAX_ACTIONS = 100_000
_HEX = re.compile(r"^[0-9a-f]{64}$")
_COMMIT = re.compile(r"^[0-9a-f]{7,64}$")
_DECISIONS = {"ALLOW", "DENY", "REQUIRE_APPROVAL"}


class ValidationError(ValueError):
    pass


def canon(obj: Any) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()


def sha256(obj: Any) -> str:
    return hashlib.sha256(canon(obj) if not isinstance(obj, (bytes, bytearray)) else obj).hexdigest()


def _hex(v: Any, what: str, *, commit: bool = False) -> str:
    if not isinstance(v, str) or not (_COMMIT if commit else _HEX).match(v):
        raise ValidationError(f"{what} must be {'a git commit hash' if commit else '64 lowercase hex characters'}")
    return v


def _num(v: Any, what: str) -> float:
    if isinstance(v, bool) or not isinstance(v, (int, float)) or v != v or v in (float("inf"), float("-inf")):
        raise ValidationError(f"{what} must be a finite number")
    return float(v)


def _scope_covers(scope: List[str], tool: str, resource: str) -> bool:
    target = f"{tool}:{resource}"
    for s in scope:
        if not isinstance(s, str):
            continue
        if s == "*" or s == target:
            return True
        if s.endswith("*") and target.startswith(s[:-1]):
            return True
    return False


def _safe_path(p: str) -> bool:
    if not isinstance(p, str) or not p or p.startswith("/") or "\\" in p or ".." in p.split("/"):
        return False
    return True


def _check_run(run: Any) -> Tuple[List[Dict[str, Any]], List[str], Dict[str, Any]]:
    """Return (checks, reasons, facts). Never raises for a malformed run; records a failed check."""
    checks: List[Dict[str, Any]] = []
    reasons: List[str] = []
    facts: Dict[str, Any] = {}

    def check(cid: str, ok: bool, detail: str = "") -> bool:
        checks.append({"id": cid, "ok": bool(ok), "detail": detail if not ok else "ok"})
        if not ok:
            reasons.append(cid + (f": {detail}" if detail else ""))
        return ok

    if not isinstance(run, dict):
        check("RUN_OBJECT", False, "run must be a JSON object")
        return checks, reasons, facts
    if run.get("schema") != SCHEMA:
        check("SCHEMA", False, f"schema must be {SCHEMA}")
    else:
        check("SCHEMA", True)

    run_id = run.get("run_id")
    check("RUN_ID", isinstance(run_id, str) and 1 <= len(run_id) <= 200, "run_id must be a non-empty string")
    tenant = run.get("tenant")
    check("TENANT", isinstance(tenant, str) and 1 <= len(tenant) <= 200, "tenant must be a non-empty string")
    agent = run.get("agent") or {}
    agent_id = agent.get("id") if isinstance(agent, dict) else None
    check("AGENT_ID", isinstance(agent_id, str) and 1 <= len(agent_id) <= 200, "agent.id must be a non-empty string")
    check("OPERATOR", isinstance(agent.get("operator") if isinstance(agent, dict) else None, str), "agent.operator is required")
    check("TASK", isinstance(run.get("task"), str) and bool(run.get("task", "").strip()), "task is required")
    repo = run.get("repo") or {}
    try:
        commit = _hex(repo.get("commit") if isinstance(repo, dict) else None, "repo.commit", commit=True)
        facts["repo_commit"] = commit
        check("REPO_COMMIT", True)
    except ValidationError as e:
        check("REPO_COMMIT", False, str(e))
    check("POLICY", isinstance(run.get("policy_revision"), str) and bool(run.get("policy_revision")), "policy_revision is required")

    try:
        started = _num(run.get("started_at"), "started_at")
        ended = _num(run.get("ended_at"), "ended_at")
        facts.update(started_at=started, ended_at=ended)
        check("TIME_ORDER", started <= ended, "started_at must be <= ended_at")
    except ValidationError as e:
        check("TIME_ORDER", False, str(e))
        started = ended = None

    actions = run.get("actions")
    if not isinstance(actions, list) or not actions:
        check("ACTIONS", False, "actions must be a non-empty list")
        actions = []
    elif len(actions) > MAX_ACTIONS:
        check("ACTIONS", False, f"too many actions ({len(actions)} > {MAX_ACTIONS})")
        actions = []
    else:
        check("ACTIONS", True)

    prev = "0" * 64
    head = prev
    for i, a in enumerate(actions):
        n = i + 1
        if not isinstance(a, dict):
            check(f"ACTION_{n}_OBJECT", False, "action must be an object")
            break
        body = {k: v for k, v in a.items() if k not in ("prev_hash", "hash")}
        body["prev_hash"] = prev
        computed = sha256(body)
        head = computed
        if a.get("seq") != n:
            check(f"ACTION_{n}_SEQ", False, f"expected seq {n}")
        if a.get("prev_hash") not in (None, prev):
            check(f"ACTION_{n}_PREV", False, "prev_hash does not match the chain")
        if a.get("hash") not in (None, computed):
            check(f"ACTION_{n}_HASH", False, "hash does not match the action body")
        try:
            at = _num(a.get("at"), "at")
            if started is not None and not (started <= at <= ended):
                check(f"ACTION_{n}_TIME", False, "action time is outside the run")
        except ValidationError as e:
            check(f"ACTION_{n}_TIME", False, str(e))
        actor = a.get("actor")
        check(f"ACTION_{n}_ACTOR", isinstance(actor, str) and bool(actor), "actor is required")
        auth = a.get("authority") or {}
        if not isinstance(auth, dict):
            check(f"ACTION_{n}_AUTHORITY", False, "authority must be an object")
        else:
            check(f"ACTION_{n}_AUTHORITY", isinstance(auth.get("grant_id"), str) and bool(auth.get("grant_id")),
                  "authority.grant_id is required")
            check(f"ACTION_{n}_SUBJECT", auth.get("subject") == actor, "authority.subject must equal action.actor")
            try:
                exp = _num(auth.get("expires_at"), "authority.expires_at")
                atv = _num(a.get("at"), "action.at")
                check(f"ACTION_{n}_EXPIRY", atv <= exp, "authority was expired when the action ran")
            except ValidationError as e:
                check(f"ACTION_{n}_EXPIRY", False, str(e))
            scope = auth.get("scope")
            tool, resource = a.get("tool"), a.get("resource")
            check(f"ACTION_{n}_SCOPE", isinstance(scope, list) and isinstance(tool, str) and isinstance(resource, str)
                  and _scope_covers(scope, tool, resource), "authority.scope does not cover tool+resource")
            check(f"ACTION_{n}_ISSUER", isinstance(auth.get("issuer"), str) and bool(auth.get("issuer")),
                  "authority.issuer is required")
        decision = a.get("decision")
        check(f"ACTION_{n}_DECISION", decision in _DECISIONS, "decision must be ALLOW, DENY or REQUIRE_APPROVAL")
        result = a.get("result")
        if decision == "ALLOW":
            check(f"ACTION_{n}_EXECUTED", result != "NOT_EXECUTED", "ALLOW action was not executed")
        elif decision in ("DENY", "REQUIRE_APPROVAL"):
            check(f"ACTION_{n}_NOT_EXECUTED", result == "NOT_EXECUTED", "a non-ALLOW action has an executed result")
        for k in ("params_digest", "result_digest"):
            v = a.get(k)
            if v not in (None, ""):
                try:
                    _hex(v, k)
                except ValidationError as e:
                    check(f"ACTION_{n}_{k.upper()}", False, str(e))
        prev = computed
    facts["action_chain_head"] = head
    facts["action_count"] = len(actions)

    tests = run.get("tests")
    if not isinstance(tests, list) or not tests:
        check("TESTS", False, "tests must be a non-empty list")
        tests = []
    else:
        check("TESTS", True)
    independent = 0
    for i, t in enumerate(tests):
        n = i + 1
        if not isinstance(t, dict):
            check(f"TEST_{n}_OBJECT", False, "test must be an object")
            continue
        author, actor = t.get("author"), (t.get("actor") or agent_id)
        if isinstance(author, str) and author and isinstance(actor, str) and author != actor:
            independent += 1
        check(f"TEST_{n}_INDEPENDENT", isinstance(author, str) and bool(author) and author != actor,
              "test author must differ from the agent that did the work")
        check(f"TEST_{n}_ORIGINAL", t.get("original_result") == "FAIL", "reference test must FAIL on the original")
        check(f"TEST_{n}_FIXED", t.get("fixed_result") == "PASS", "reference test must PASS on the fixed artifact")
        check(f"TEST_{n}_COMMAND", isinstance(t.get("command"), str) and bool(t.get("command")), "test command is required")
        try:
            _hex(t.get("artifact_digest"), "test.artifact_digest")
        except ValidationError as e:
            check(f"TEST_{n}_ARTIFACT", False, str(e))
    check("INDEPENDENT_TEST", independent >= 1, "no test was authored independently of the agent")

    artifacts = run.get("artifacts")
    if not isinstance(artifacts, list) or not artifacts:
        check("ARTIFACTS", False, "artifacts must be a non-empty list")
    else:
        ok = True
        for i, a in enumerate(artifacts):
            if not isinstance(a, dict) or not _safe_path(a.get("path")):
                check(f"ARTIFACT_{i+1}_PATH", False, "unsafe or missing artifact path"); ok = False; continue
            try:
                _hex(a.get("sha256"), "artifact.sha256")
            except ValidationError as e:
                check(f"ARTIFACT_{i+1}_SHA256", False, str(e)); ok = False
        check("ARTIFACTS", ok)
    return checks, reasons, facts


def evaluate(run: Any):
    """(verdict, checks, extra) for the try-it route and the offline verifier. Never raises."""
    try:
        checks, reasons, facts = _check_run(run)
    except Exception as e:  # noqa: BLE001 - an input the checks cannot walk is refused, never passed
        return "NOT_VERIFIED", [{"id": "RUN_ERROR", "ok": False, "detail": f"{type(e).__name__}: {e}"[:200]}], {}
    return ("VERIFIED_RUN" if not reasons else "NOT_VERIFIED"), checks, facts


#!/usr/bin/env python3
"""Offline verifier for a CAIN-A75-001 Long-Run Engineering Attestation.

Imports no CAIN code. Standard library plus `cryptography` for Ed25519 verification.
    python3 verify_offline.py attestation.json [--pinned-key BASE64]
"""

import argparse
import base64
import hashlib
import json
import sys
from pathlib import Path


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()


def sha(o):
    return hashlib.sha256(canon(o)).hexdigest()


def check_scope(scope, tool, resource):
    target = f"{tool}:{resource}"
    for s in scope:
        if not isinstance(s, str):
            continue
        if s in ("*", target) or (s.endswith("*") and target.startswith(s[:-1])):
            return True
    return False


def verify(att, pinned=None):
    bad = []
    if not isinstance(att, dict):
        return ["attestation is not an object"]
    sig, pub = att.get("signature_b64"), att.get("public_key_b64")
    body = {k: v for k, v in att.items() if k != "signature_b64"}
    if pinned and pub != pinned:
        bad.append("PUBLIC_KEY_NOT_PINNED")
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(base64.b64decode(pub, validate=True)).verify(
            base64.b64decode(sig, validate=True), canon(body))
    except Exception:
        bad.append("INVALID_SIGNATURE")
    if att.get("attestation_id") != sha({k: v for k, v in body.items() if k != "attestation_id"}):
        bad.append("ATTESTATION_ID_MISMATCH")
    run = att.get("run") or {}
    actions = run.get("actions") or []
    prev = "0" * 64
    for i, a in enumerate(actions, 1):
        if not isinstance(a, dict):
            bad.append(f"ACTION_{i}_NOT_OBJECT"); break
        b = {k: v for k, v in a.items() if k not in ("prev_hash", "hash")}
        b["prev_hash"] = prev
        h = sha(b)
        if a.get("seq") != i:
            bad.append(f"ACTION_{i}_SEQ")
        if a.get("prev_hash") not in (None, prev):
            bad.append(f"ACTION_{i}_PREV")
        if a.get("hash") not in (None, h):
            bad.append(f"ACTION_{i}_HASH")
        auth = a.get("authority") or {}
        if auth.get("subject") != a.get("actor"):
            bad.append(f"ACTION_{i}_SUBJECT")
        if not check_scope(auth.get("scope") or [], a.get("tool"), a.get("resource")):
            bad.append(f"ACTION_{i}_SCOPE")
        try:
            if float(a.get("at")) > float(auth.get("expires_at")):
                bad.append(f"ACTION_{i}_EXPIRY")
        except (TypeError, ValueError):
            bad.append(f"ACTION_{i}_EXPIRY")
        if a.get("decision") == "ALLOW" and a.get("result") == "NOT_EXECUTED":
            bad.append(f"ACTION_{i}_EXECUTED")
        if a.get("decision") in ("DENY", "REQUIRE_APPROVAL") and a.get("result") != "NOT_EXECUTED":
            bad.append(f"ACTION_{i}_NOT_EXECUTED")
        prev = h
    agent = (run.get("agent") or {}).get("id")
    tests = run.get("tests") or []
    if not any(isinstance(t, dict) and t.get("author") and t.get("author") != (t.get("actor") or agent)
               and t.get("original_result") == "FAIL" and t.get("fixed_result") == "PASS" for t in tests):
        bad.append("NO_INDEPENDENT_TEST")
    if not (run.get("artifacts") or []):
        bad.append("NO_ARTIFACTS")
    want = "VERIFIED_RUN" if not bad else "NOT_VERIFIED"
    if att.get("verdict", {}).get("status") != want:
        bad.append("VERDICT_MISMATCH")
    rerun = globals().get("evaluate")   # present when the published rules are embedded above this verifier
    if rerun is not None:
        v, checks, _ = rerun(att.get("run"))
        if v != att.get("verdict", {}).get("status") or checks != att.get("verdict", {}).get("checks"):
            bad.append("RULES_RERUN_MISMATCH")
    return bad


def main(argv=None):
    ap = argparse.ArgumentParser()
    ap.add_argument("attestation", nargs="?", default="attestation.json")
    ap.add_argument("--pinned-key", default=None)
    a = ap.parse_args(argv)
    p = Path(a.attestation)
    try:
        att = json.loads(p.read_text())
    except (OSError, ValueError) as e:
        print(f"FAIL  cannot read {p}: {e}")
        return 1
    bad = verify(att, a.pinned_key)
    status = att.get("verdict", {}).get("status", "?")
    print(f"attestation: {att.get('attestation_id', '?')}")
    print(f"verdict:     {status}")
    print(f"signature:   {'PASS' if 'INVALID_SIGNATURE' not in bad else 'FAIL'}")
    for b in bad:
        print(f"FAIL  {b}")
    print(f"\n{'PASS  0 failures' if not bad else str(len(bad)) + ' failure(s)'}")
    return 0 if not bad else 1


if __name__ == "__main__":
    raise SystemExit(main())
