"""Spurvik EU AI Act helper for Python 3.10+ (FastAPI, Django, LangChain, PydanticAI, OpenAI SDK).

MIT License - Copyright (c) 2026 EyeTea Solutions ApS (https://spurvik.com)
Zero third-party dependencies (uses Python stdlib only).

Capabilities:
1. Keyed HMAC-SHA256 digests (`keyed_digest`, `build_telemetry_event`) with 0 bytes of raw prompt or
   completion text sent over the network (supports EU AI Act Art. 12 & GDPR Art. 5(1)(c)).
2. Canonical `spurvik.payload_summary.v1` field-names-only summaries (`build_payload_summary`),
   hosted pre-execution human approval requests (`request_human_approval`, Pro/Team, Art. 14), and
   wire-compatible signed callback verification (`create_signed_approval_links`,
   `verify_signed_callback`, `run_gate_self_test` — byte-identical to `spurvik/channels` in Node.js).
3. HTML script helper (`art50_badge_html`) for Jinja2 / Django templates across all 24 official EU
   languages (`https://spurvik.com/badge.js`, Art. 50(1)).

Zero-key offline 6-vector Art. 14 blocking self-test:
    python3 spurvik_guard.py [domain] [--json]

Environment variables:
- SPURVIK_API_KEY: Project key from https://console.spurvik.com/signup (Free EUR 0: 10k events/mo)
- SPURVIK_CONTENT_HASH_SECRET: Server-local secret (>= 16 UTF-8 bytes) that never leaves your server
- SPURVIK_SIGNING_SECRET: Optional dedicated secret (>= 16 chars) for signed Art. 14 callback links
"""

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime, timezone
import hashlib
import hmac
import html
import json
import os
import re
import secrets
import sys
import time
from typing import Any, Iterable, Mapping, Sequence
import urllib.parse
import urllib.request
import uuid

SPURVIK_VERSION = "1.0.14"
CONSOLE_BASE_URL = "https://console.spurvik.com"
BADGE_SCRIPT_SRC = "https://spurvik.com/badge.js"
PAYLOAD_SUMMARY_SCHEMA = "spurvik.payload_summary.v1"

EU_LOCALES: frozenset[str] = frozenset({
    "bg", "cs", "da", "de", "el", "en", "es", "et", "fi", "fr", "ga", "hr",
    "hu", "it", "lt", "lv", "mt", "nl", "pl", "pt", "ro", "sk", "sl", "sv",
})
NOTICE_KINDS: frozenset[str] = frozenset({
    "interaction", "generated", "deepfake", "public-interest", "emotion-biometric",
})
BADGE_POSITIONS: frozenset[str] = frozenset({
    "bottom-right", "bottom-left", "top-right", "top-left", "inline",
})

_KEY_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
_HEX64_RE = re.compile(r"^[0-9a-f]{64}$")
_MAX_SUMMARY_CHARS = 500
_MAX_SUMMARY_KEYS = 32


def _resolve_hash_secret(secret: str | bytes | None = None) -> bytes:
    raw = secret if secret is not None else os.environ.get("SPURVIK_CONTENT_HASH_SECRET", "")
    key = raw.encode("utf-8") if isinstance(raw, str) else bytes(raw)
    if len(key) < 16:
        raise ValueError("SPURVIK_CONTENT_HASH_SECRET must be at least 16 UTF-8 bytes.")
    return key


def keyed_digest(text: str, *, secret: str | bytes | None = None) -> str:
    """Return a 64-char lowercase hex HMAC-SHA256 fingerprint using a secret kept on your server."""
    key = _resolve_hash_secret(secret)
    return hmac.new(key, str(text).encode("utf-8"), hashlib.sha256).hexdigest()


def build_payload_summary(
    payload_or_keys: Mapping[str, Any] | Iterable[str],
    *,
    content_fingerprint: str | None = None,
) -> str:
    """Build canonical `spurvik.payload_summary.v1` JSON containing sorted object keys and field names only."""
    raw_keys: Sequence[str] = (
        list(payload_or_keys.keys())
        if isinstance(payload_or_keys, Mapping)
        else list(payload_or_keys)
    )
    valid_keys = [k for k in raw_keys if isinstance(k, str) and _KEY_RE.match(k)][
        :_MAX_SUMMARY_KEYS
    ]
    fp = (
        content_fingerprint
        if isinstance(content_fingerprint, str) and _HEX64_RE.match(content_fingerprint)
        else None
    )

    def _render(kept: list[str]) -> str:
        doc = {
            "contentFingerprint": fp,
            "keys": kept,
            "schema": PAYLOAD_SUMMARY_SCHEMA,
        }
        return json.dumps(doc, separators=(",", ":"), sort_keys=True, ensure_ascii=False)

    kept = list(valid_keys)
    serialized = _render(kept)
    while len(serialized) > _MAX_SUMMARY_CHARS and kept:
        kept.pop()
        serialized = _render(kept)
    return serialized


def build_telemetry_event(
    prompt: str,
    output: str,
    *,
    model_provider: str = "openai",
    model_version: str = "gpt-4o",
    latency_ms: int = 0,
    temperature: float | None = None,
    content_marking_applied: bool = False,
    marking_hook_id: str | None = None,
    hitl_status: str | None = "not_required",
    secret: str | bytes | None = None,
) -> dict[str, Any]:
    """Build a single event dict accepted by POST /api/v1/telemetry (no raw prompt or output fields)."""
    ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
    clamped_latency = max(0, min(3_600_000, int(latency_ms)))
    return {
        "eventId": str(uuid.uuid4()),
        "timestamp": ts,
        "modelProvider": str(model_provider)[:64] or "custom",
        "modelVersion": str(model_version)[:200] or "unknown",
        "inputHash": keyed_digest(prompt, secret=secret),
        "outputHash": keyed_digest(output, secret=secret),
        "contentHashMode": "keyed",
        "latencyMs": clamped_latency,
        "temperature": float(temperature) if temperature is not None else None,
        "contentMarkingApplied": bool(content_marking_applied),
        "markingHookId": str(marking_hook_id)[:120] if marking_hook_id else None,
        "hitlStatus": hitl_status,
    }


def _post_json(
    path: str,
    body: dict[str, Any],
    *,
    api_key: str | None = None,
    base_url: str = CONSOLE_BASE_URL,
    timeout_sec: float = 5.0,
) -> dict[str, Any]:
    token = (api_key or os.environ.get("SPURVIK_API_KEY", "")).strip()
    if not token:
        raise ValueError(
            "SPURVIK_API_KEY is missing. Create a free key at https://console.spurvik.com/signup"
        )
    url = base_url.rstrip("/") + path
    if not url.startswith("https://") and not url.startswith("http://localhost"):
        raise ValueError("Spurvik base_url must use https:// (or http://localhost in local tests).")
    req = urllib.request.Request(
        url,
        data=json.dumps(body, separators=(",", ":")).encode("utf-8"),
        headers={
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json",
            "Accept": "application/json",
            "User-Agent": f"spurvik-python/{SPURVIK_VERSION}",
        },
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=timeout_sec) as resp:  # noqa: S310
        raw = resp.read().decode("utf-8")
        return json.loads(raw) if raw else {}


def send_telemetry_event(
    prompt: str,
    output: str,
    *,
    model_provider: str = "openai",
    model_version: str = "gpt-4o",
    latency_ms: int = 0,
    temperature: float | None = None,
    content_marking_applied: bool = False,
    hitl_status: str | None = "not_required",
    api_key: str | None = None,
    secret: str | bytes | None = None,
    base_url: str = CONSOLE_BASE_URL,
) -> dict[str, Any]:
    """Send a keyed HMAC-SHA256 telemetry receipt to the EU Frankfurt vault (POST /api/v1/telemetry)."""
    event = build_telemetry_event(
        prompt,
        output,
        model_provider=model_provider,
        model_version=model_version,
        latency_ms=latency_ms,
        temperature=temperature,
        content_marking_applied=content_marking_applied,
        hitl_status=hitl_status,
        secret=secret,
    )
    return _post_json("/api/v1/telemetry", {"events": [event]}, api_key=api_key, base_url=base_url)


def request_human_approval(
    action_name: str,
    payload_or_keys: Mapping[str, Any] | Iterable[str],
    *,
    content_fingerprint: str | None = None,
    api_key: str | None = None,
    base_url: str = CONSOLE_BASE_URL,
) -> dict[str, Any]:
    """Enqueue a pre-execution Art. 14 human approval item (Pro EUR 19/mo & Team EUR 79/mo)."""
    name = str(action_name).strip()[:200]
    if not name:
        raise ValueError("action_name must not be empty.")
    summary = build_payload_summary(payload_or_keys, content_fingerprint=content_fingerprint)
    return _post_json(
        "/api/v1/hitl",
        {"actionName": name, "payloadSummary": summary},
        api_key=api_key,
        base_url=base_url,
    )


def art50_badge_html(
    *,
    system_name: str = "AI Assistant",
    locale: str = "en",
    notice: str = "interaction",
    position: str = "bottom-right",
    white_label: bool = False,
) -> str:
    """Return a safe HTML `<script>` tag for Jinja2 / Django templates (`https://spurvik.com/badge.js`)."""
    safe_locale = locale.lower() if locale and locale.lower() in EU_LOCALES else "en"
    safe_notice = notice if notice in NOTICE_KINDS else "interaction"
    safe_pos = position if position in BADGE_POSITIONS else "bottom-right"
    clean_sys = re.sub(r"[\x00-\x1f\x7f]+", " ", str(system_name)).strip()[:80] or "AI Assistant"
    escaped_sys = html.escape(clean_sys, quote=True)
    attr = "false" if white_label else "true"
    return (
        f'<script src="{BADGE_SCRIPT_SRC}" data-system="{escaped_sys}" '
        f'data-notice="{safe_notice}" data-locale="{safe_locale}" '
        f'data-position="{safe_pos}" data-attribution="{attr}" defer></script>'
    )


_DEFAULT_LINK_MAX_AGE_SECONDS = 86_400
_MAX_LINK_MAX_AGE_SECONDS = 7 * 24 * 60 * 60
_MAX_CLOCK_SKEW_SECONDS = 300
_HOST_RE = re.compile(
    r"^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$"
)


def _resolve_signing_secret(signing_secret: str | None = None) -> str:
    raw = (
        signing_secret
        if signing_secret is not None
        else (
            os.environ.get("SPURVIK_SIGNING_SECRET")
            or os.environ.get("SPURVIK_CONTENT_HASH_SECRET")
            or ""
        )
    )
    if not isinstance(raw, str) or len(raw) == 0:
        raise ValueError("Channel approval signing_secret is missing.")
    if raw != raw.strip():
        raise ValueError("Channel approval signing_secret must not have leading or trailing whitespace.")
    if len(raw) < 16:
        raise ValueError("Channel approval signing_secret must be at least 16 characters.")
    return raw


def _decision_mac_payload(
    gate_id: str,
    action_hmac: str,
    decision: str,
    issued_at_unix: int,
    nonce: str | None = None,
) -> str:
    base = f"spurvik:art14:decision:v1|{gate_id}|{action_hmac}|{decision}|{issued_at_unix}"
    if isinstance(nonce, str) and len(nonce) > 0:
        return f"{base}|{nonce}"
    return base


def compute_action_hmac(
    gate_id: str,
    action_name: str,
    context: Mapping[str, str | int | float | bool] | None = None,
    *,
    signing_secret: str | None = None,
) -> str:
    """Compute the deterministic `spurvik:art12:v1` action HMAC matching `spurvik/channels`."""
    sec = _resolve_signing_secret(signing_secret)
    pairs = "&".join(
        f"{k}={('true' if v is True else 'false' if v is False else str(v))}"
        for k, v in sorted((context or {}).items(), key=lambda kv: kv[0])
    )
    msg = f"spurvik:art12:v1|{gate_id}|{action_name}|{pairs}".encode("utf-8")
    return hmac.new(sec.encode("utf-8"), msg, hashlib.sha256).hexdigest()


def create_signed_approval_links(
    *,
    gate_id: str,
    action_name: str,
    callback_base_url: str,
    context: Mapping[str, str | int | float | bool] | None = None,
    signing_secret: str | None = None,
    issued_at_unix: int | None = None,
    nonce: str | None = None,
) -> dict[str, Any]:
    """Mint signed Approve / Block callback URLs wire-compatible with `spurvik/channels`."""
    sec = _resolve_signing_secret(signing_secret)
    base = str(callback_base_url or "").strip().rstrip("/")
    if not base:
        raise ValueError("callback_base_url is required.")
    ts = int(time.time()) if issued_at_unix is None else int(issued_at_unix)
    tok_nonce = nonce if isinstance(nonce, str) and len(nonce) > 0 else secrets.token_hex(16)
    action_hmac = compute_action_hmac(gate_id, action_name, context, signing_secret=sec)
    approve_token = hmac.new(
        sec.encode("utf-8"),
        _decision_mac_payload(gate_id, action_hmac, "approved", ts, tok_nonce).encode("utf-8"),
        hashlib.sha256,
    ).hexdigest()
    reject_token = hmac.new(
        sec.encode("utf-8"),
        _decision_mac_payload(gate_id, action_hmac, "rejected", ts, tok_nonce).encode("utf-8"),
        hashlib.sha256,
    ).hexdigest()
    q = (
        f"gateId={urllib.parse.quote(gate_id, safe='')}&ts={ts}"
        f"&hmac={action_hmac}&nonce={urllib.parse.quote(tok_nonce, safe='')}"
    )
    return {
        "gateId": gate_id,
        "actionName": action_name,
        "actionHmac": action_hmac,
        "approveToken": approve_token,
        "rejectToken": reject_token,
        "approveUrl": f"{base}?{q}&decision=approved&sig={approve_token}",
        "rejectUrl": f"{base}?{q}&decision=rejected&sig={reject_token}",
        "nonce": tok_nonce,
        "issuedAtUnix": ts,
    }


def verify_signed_callback(
    url_or_params: str | Mapping[str, Any],
    *,
    signing_secret: str | None = None,
    expected_action_hmac: str | None = None,
    max_age_seconds: int = _DEFAULT_LINK_MAX_AGE_SECONDS,
    now_unix_seconds: int | None = None,
) -> dict[str, Any] | None:
    """Verify a signed Approve / Block callback link in constant time (fail-closed -> `None`)."""
    sec = _resolve_signing_secret(signing_secret)
    if max_age_seconds == 0:
        raise ValueError("max_age_seconds must be greater than 0.")
    max_age = (
        min(int(max_age_seconds), _MAX_LINK_MAX_AGE_SECONDS)
        if isinstance(max_age_seconds, (int, float)) and max_age_seconds > 0
        else _DEFAULT_LINK_MAX_AGE_SECONDS
    )
    now = int(time.time()) if now_unix_seconds is None else int(now_unix_seconds)

    if isinstance(url_or_params, str):
        raw = url_or_params.strip()
        qs = raw.split("?", 1)[1] if "?" in raw else raw
        parsed = {k: v[0] for k, v in urllib.parse.parse_qs(qs, keep_blank_values=True).items() if v}
        gate_id = parsed.get("gateId")
        action_hmac = parsed.get("hmac") or parsed.get("actionHmac")
        decision = parsed.get("decision")
        raw_ts = parsed.get("ts") or parsed.get("issuedAtUnix")
        signature = parsed.get("sig") or parsed.get("signature")
        nonce = parsed.get("nonce") or None
    elif isinstance(url_or_params, Mapping):
        gate_id = url_or_params.get("gateId")
        action_hmac = url_or_params.get("actionHmac") or url_or_params.get("hmac")
        decision = url_or_params.get("decision")
        raw_ts = url_or_params.get("issuedAtUnix", url_or_params.get("ts"))
        signature = url_or_params.get("signature") or url_or_params.get("sig")
        raw_nonce = url_or_params.get("nonce")
        nonce = raw_nonce if isinstance(raw_nonce, str) and len(raw_nonce) > 0 else None
    else:
        return None

    if not isinstance(signature, str) or not _HEX64_RE.match(signature):
        return None
    if not isinstance(gate_id, str) or not gate_id:
        return None
    if not isinstance(action_hmac, str) or not _HEX64_RE.match(action_hmac):
        return None
    if decision not in ("approved", "rejected"):
        return None
    try:
        issued_at = int(str(raw_ts).strip())
    except (TypeError, ValueError):
        return None

    if now - issued_at > max_age or issued_at - now > _MAX_CLOCK_SKEW_SECONDS:
        return None
    if expected_action_hmac is not None:
        if not isinstance(expected_action_hmac, str) or not hmac.compare_digest(
            action_hmac, expected_action_hmac
        ):
            return None

    expected_sig = hmac.new(
        sec.encode("utf-8"),
        _decision_mac_payload(gate_id, action_hmac, decision, issued_at, nonce).encode("utf-8"),
        hashlib.sha256,
    ).hexdigest()
    if not hmac.compare_digest(signature, expected_sig):
        return None

    return {
        "ok": True,
        "decision": decision,
        "gateId": gate_id,
        "actionHmac": action_hmac,
        "issuedAtUnix": issued_at,
        "nonce": nonce,
    }


def run_gate_self_test(domain: str = "acme.eu") -> dict[str, Any]:
    """Run 6 offline cryptographic Art. 14 fail-closed blocking vectors (0 network calls, 0 keys)."""
    raw_host = re.sub(r"^https?://", "", str(domain or "").strip().lower()).split("/", 1)[0]
    host = raw_host if _HOST_RE.match(raw_host) else "acme.eu"
    secret = "spurvik-self-test-ephemeral-32b!"
    ts = 1_764_000_000
    links = create_signed_approval_links(
        gate_id="gate_refund_01",
        action_name="stripe.refunds.create",
        callback_base_url=f"https://{host}/api/spurvik/callback",
        context={"amountEur": 420, "currency": "EUR"},
        signing_secret=secret,
        issued_at_unix=ts,
        nonce="0123456789abcdef0123456789abcdef",
    )
    tampered_hmac = compute_action_hmac(
        "gate_refund_01",
        "stripe.refunds.create",
        {"amountEur": 42000, "currency": "EUR"},
        signing_secret=secret,
    )

    v1 = verify_signed_callback("", signing_secret=secret, expected_action_hmac=links["actionHmac"], now_unix_seconds=ts + 5)
    v2 = verify_signed_callback(links["rejectUrl"], signing_secret=secret, expected_action_hmac=links["actionHmac"], now_unix_seconds=ts + 5)
    v3 = verify_signed_callback(links["approveUrl"], signing_secret=secret, expected_action_hmac=tampered_hmac, now_unix_seconds=ts + 5)
    flipped_url = links["rejectUrl"].replace("decision=rejected", "decision=approved")
    v4 = verify_signed_callback(flipped_url, signing_secret=secret, expected_action_hmac=links["actionHmac"], now_unix_seconds=ts + 5)
    v5 = verify_signed_callback(links["approveUrl"], signing_secret=secret, expected_action_hmac=links["actionHmac"], max_age_seconds=900, now_unix_seconds=ts + 901)
    v6 = verify_signed_callback(links["approveUrl"], signing_secret=secret, expected_action_hmac=links["actionHmac"], max_age_seconds=900, now_unix_seconds=ts + 12)

    vectors = [
        {"id": "unapproved_default_halt", "blocked": v1 is None, "passed": v1 is None, "detail": "No signed human token -> tool execution halted"},
        {"id": "explicit_human_block", "blocked": bool(v2 and v2["decision"] == "rejected"), "passed": bool(v2 and v2["decision"] == "rejected"), "detail": "Signed Block token -> decision=rejected enforced"},
        {"id": "tampered_payload_hmac", "blocked": v3 is None, "passed": v3 is None, "detail": "EUR 420 -> EUR 42,000 payload mismatch rejected"},
        {"id": "decision_flip_forgery", "blocked": v4 is None, "passed": v4 is None, "detail": "rejected -> approved query-string flip rejected"},
        {"id": "expired_link_replay", "blocked": v5 is None, "passed": v5 is None, "detail": "+901s past 900s max_age_seconds window rejected"},
        {"id": "authentic_signed_approval", "blocked": False, "passed": bool(v6 and v6["decision"] == "approved"), "detail": "Constant-time HMAC-SHA256 + actionHmac verified"},
    ]
    passed = sum(1 for v in vectors if v["passed"])
    q_app = f"&appUrl={urllib.parse.quote(host, safe='')}"
    return {
        "ok": passed == len(vectors),
        "version": SPURVIK_VERSION,
        "domain": host,
        "passed": passed,
        "total": len(vectors),
        "actionHmac": links["actionHmac"],
        "vectors": vectors,
        "plans": {
            "free": f"{CONSOLE_BASE_URL}/signup?plan=free{q_app}",
            "proMonthlyEur19": f"{CONSOLE_BASE_URL}/signup?plan=pro{q_app}",
            "proAnnualEur190": f"{CONSOLE_BASE_URL}/signup?plan=pro&interval=annual{q_app}",
            "teamMonthlyEur79": f"{CONSOLE_BASE_URL}/signup?plan=team{q_app}",
            "teamAnnualEur790": f"{CONSOLE_BASE_URL}/signup?plan=team&interval=annual{q_app}",
            "doneForYouEur199": f"{CONSOLE_BASE_URL}/signup?plan=concierge{q_app}",
        },
        "cockpitUrl": f"https://spurvik.com/langgraph-openai-agents-approval-check?domain={urllib.parse.quote(host, safe='')}",
    }


@dataclass(frozen=True)
class SpurvikGuard:
    """Ergonomic zero-dependency client wrapper mirroring the Console project quickstart (`SpurvikGuard.from_env`)."""

    system_name: str = "AI Assistant"
    locale: str = "en"
    api_key: str | None = None
    content_hash_secret: str | bytes | None = None
    signing_secret: str | None = None
    base_url: str = CONSOLE_BASE_URL

    @classmethod
    def from_env(
        cls,
        *,
        system_name: str = "AI Assistant",
        locale: str = "en",
    ) -> SpurvikGuard:
        return cls(
            system_name=system_name,
            locale=locale,
            api_key=os.environ.get("SPURVIK_API_KEY") or None,
            content_hash_secret=os.environ.get("SPURVIK_CONTENT_HASH_SECRET") or None,
            signing_secret=os.environ.get("SPURVIK_SIGNING_SECRET") or None,
            base_url=os.environ.get("SPURVIK_BASE_URL") or CONSOLE_BASE_URL,
        )

    def build_event(
        self,
        prompt_text: str,
        output_text: str,
        *,
        model: str = "gpt-4o",
        provider: str = "openai",
        latency_ms: int = 0,
        temperature: float | None = None,
        content_marking_applied: bool = False,
        hitl_status: str | None = "not_required",
    ) -> dict[str, Any]:
        return build_telemetry_event(
            prompt_text,
            output_text,
            model_provider=provider,
            model_version=model,
            latency_ms=latency_ms,
            temperature=temperature,
            content_marking_applied=content_marking_applied,
            hitl_status=hitl_status,
            secret=self.content_hash_secret,
        )

    def log_call(
        self,
        prompt_text: str,
        output_text: str,
        *,
        model: str = "gpt-4o",
        provider: str = "openai",
        latency_ms: int = 0,
        temperature: float | None = None,
        content_marking_applied: bool = False,
        hitl_status: str | None = "not_required",
    ) -> dict[str, Any]:
        return send_telemetry_event(
            prompt_text,
            output_text,
            model_provider=provider,
            model_version=model,
            latency_ms=latency_ms,
            temperature=temperature,
            content_marking_applied=content_marking_applied,
            hitl_status=hitl_status,
            api_key=self.api_key,
            secret=self.content_hash_secret,
            base_url=self.base_url,
        )

    def badge_html(
        self,
        *,
        notice: str = "interaction",
        position: str = "bottom-left",
        white_label: bool = False,
    ) -> str:
        return art50_badge_html(
            system_name=self.system_name,
            locale=self.locale,
            notice=notice,
            position=position,
            white_label=white_label,
        )

    def request_approval(
        self,
        action_name: str,
        payload_or_keys: Mapping[str, Any] | Iterable[str],
        *,
        content_fingerprint: str | None = None,
    ) -> dict[str, Any]:
        return request_human_approval(
            action_name,
            payload_or_keys,
            content_fingerprint=content_fingerprint,
            api_key=self.api_key,
            base_url=self.base_url,
        )

    def verify_callback(
        self,
        callback_url_or_query: str,
        *,
        expected_action_hmac: str | None = None,
        max_age_seconds: int = _DEFAULT_LINK_MAX_AGE_SECONDS,
        now_unix_seconds: int | None = None,
    ) -> dict[str, Any] | None:
        return verify_signed_callback(
            callback_url_or_query,
            signing_secret=self.signing_secret,
            expected_action_hmac=expected_action_hmac,
            max_age_seconds=max_age_seconds,
            now_unix_seconds=now_unix_seconds,
        )


def _cli(argv: Sequence[str]) -> int:
    args = [a for a in argv if a not in ("--gate", "gate", "block-test", "--self-test")]
    as_json = "--json" in args
    positional = [a for a in args if not a.startswith("-")]
    res = run_gate_self_test(positional[0] if positional else "acme.eu")
    if as_json:
        print(json.dumps(res, indent=2))
        return 0 if res["ok"] else 1
    print(f"Spurvik Python Guard v{res['version']} - Art. 14 Blocking Self-Test ({res['domain']})")
    print(f"Action HMAC (spurvik:art12:v1, 0 raw prompt bytes): {res['actionHmac']}")
    for v in res["vectors"]:
        outcome = "BLOCKED  " if v["blocked"] else "PERMITTED"
        mark = "PASS" if v["passed"] else "FAIL"
        print(f"  [{mark}] {outcome}  {v['id']}: {v['detail']}")
    print(f"Result: {res['passed']}/{res['total']} vectors passed (5 blocked fail-closed, 1 authentic approval permitted).")
    print(f"Interactive Art. 14 cockpit: {res['cockpitUrl']}")
    print(f"Free EUR 0 (10k/mo, 30d): {res['plans']['free']}")
    print(f"Pro EUR 19/mo or EUR 190/yr (250k/mo, 90d, Slack & Teams HITL): {res['plans']['proMonthlyEur19']}")
    print(f"Team EUR 79/mo or EUR 790/yr (2M/mo, 12mo, Annex IV draft): {res['plans']['teamMonthlyEur79']}")
    return 0 if res["ok"] else 1


if __name__ == "__main__":
    raise SystemExit(_cli(sys.argv[1:]))
