# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-an-a2a-v1-0-push-notification-webhook-as-unauthenticated-until-the-task-scoped-jwt-audience-and-taskid-contextid-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-an-a2a-v1-0-push-notification-webhook-as-unauthenticated-until-the-task-scoped-jwt-audience-and-taskid-contextid-binding.warrant.json
# Markdown SHA-256:   ca7c0a9c5cb5d69cb3360987dfa060fb380c954e502139caa60baf23928ed84f
# Code AST SHA-256:   a30782672a9ac4f7038c636e84e949aa986b6ee5ac34664a80651898a52b483e
# Verified Classes:   WebhookAuthorizationError, Registration, TaskRecord, WebhookEvent, WebhookGate
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass, field
from typing import Literal

TaskState = Literal["submitted", "working", "input-required", "auth-required", "completed", "failed", "canceled"]
TERMINAL: frozenset[TaskState] = frozenset({"completed", "failed", "canceled"})
LEGAL: dict[TaskState, frozenset[TaskState]] = {
    "submitted": frozenset({"working", "failed", "canceled"}),
    "working": frozenset({"working", "input-required", "auth-required", "completed", "failed", "canceled"}),
    "input-required": frozenset({"working", "failed", "canceled"}),
    "auth-required": frozenset({"working", "failed", "canceled"}),
    "completed": frozenset(),
    "failed": frozenset(),
    "canceled": frozenset(),
}


class WebhookAuthorizationError(RuntimeError):
    """Raised when an inbound A2A push-notification event cannot be bound to a
    live registration under C1-C5. The event must be downgraded to a reconcile
    hint, never committed to the task FSM."""


@dataclass(frozen=True)
class Registration:
    task_id: str
    context_id: str
    webhook_url: str
    pinned_jwks_uri: str          # resolved out-of-band; card refresh may NOT change it
    audience: str                 # per-registration, not per-host
    registration_nonce: str       # defeats taskId reuse
    created_at: float


@dataclass
class TaskRecord:
    task_id: str
    context_id: str
    state: TaskState
    registration_nonce: str
    artifacts: list[str] = field(default_factory=list)


@dataclass(frozen=True)
class WebhookEvent:
    task_id: str
    context_id: str
    claimed_state: TaskState
    jwt_aud: str
    jwt_iss: str
    jwks_uri_used: str
    registration_nonce: str
    iat: float
    exp: float
    jti: str
    artifacts: tuple[str, ...] = ()


class WebhookGate:
    def __init__(self, max_skew_s: float = 300.0) -> None:
        self._records: dict[str, TaskRecord] = {}
        self._registrations: dict[str, Registration] = {}
        self._seen_jti: set[str] = set()
        self._max_skew = max_skew_s

    def register(self, reg: Registration) -> None:
        self._registrations[reg.task_id] = reg
        self._records[reg.task_id] = TaskRecord(
            task_id=reg.task_id,
            context_id=reg.context_id,
            state="submitted",
            registration_nonce=reg.registration_nonce,
        )

    def handle(self, ev: WebhookEvent, now: float | None = None) -> TaskState:
        now = now if now is not None else time.time()
        reg = self._registrations.get(ev.task_id)
        rec = self._records.get(ev.task_id)

        # C5: liveness + id-reuse guard
        if reg is None or rec is None:
            raise WebhookAuthorizationError(
                f"no live registration for taskId={ev.task_id!r}; event is a reconcile hint only"
            )
        if rec.registration_nonce != ev.registration_nonce:
            raise WebhookAuthorizationError(
                f"registration nonce mismatch for taskId={ev.task_id!r} "
                f"(recycled id or stale registration)"
            )

        # C1: exact (taskId, contextId) binding against OUR record, not the card
        if ev.context_id != rec.context_id:
            raise WebhookAuthorizationError(
                f"contextId splice: event={ev.context_id!r} record={rec.context_id!r} "
                f"for taskId={ev.task_id!r}"
            )

        # C2: per-registration audience, not host-level
        if ev.jwt_aud != reg.audience:
            raise WebhookAuthorizationError(
                f"audience mismatch for taskId={ev.task_id!r}: "
                f"got {ev.jwt_aud!r} expected {reg.audience!r}"
            )

        # C3: key resolution must not have been re-pointed by a card refresh
        if ev.jwks_uri_used != reg.pinned_jwks_uri:
            raise WebhookAuthorizationError(
                f"JWKS re-pointed via card trust loop for taskId={ev.task_id!r}: "
                f"used {ev.jwks_uri_used!r} pinned {reg.pinned_jwks_uri!r}"
            )

        # C4: freshness + replay
        if not (ev.iat - self._max_skew <= now <= ev.exp + self._max_skew):
            raise WebhookAuthorizationError(
                f"event outside freshness window for taskId={ev.task_id!r}"
            )
        if ev.jti in self._seen_jti:
            raise WebhookAuthorizationError(f"replayed jti={ev.jti!r}")

        # FSM transition legality + terminal absorbing
        if rec.state in TERMINAL:
            raise WebhookAuthorizationError(
                f"transition from terminal state {rec.state!r} for taskId={ev.task_id!r}"
            )
        if ev.claimed_state not in LEGAL[rec.state]:
            raise WebhookAuthorizationError(
                f"illegal transition {rec.state!r}->{ev.claimed_state!r} for taskId={ev.task_id!r}"
            )

        # Commit
        self._seen_jti.add(ev.jti)
        rec.state = ev.claimed_state
        rec.artifacts.extend(ev.artifacts)
        return rec.state
