# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-a-webhook-delivery-contract-mismatch-during-a2a-task-state-replay-after-an-agent-card-capability-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-a-webhook-delivery-contract-mismatch-during-a2a-task-state-replay-after-an-agent-card-capability-refresh.warrant.json
# Markdown SHA-256:   60a4bb1b67dbde327987ff38e0fc809368a36b97aadbd1233b57339d681ab2e6
# Code AST SHA-256:   6ee40fe06d9ac00fd21ccefa62a8682ac100a157e2dc1e1e8648af77587b611d
# Verified Classes:   ContractMismatchError, TaskState, PushContract, TaskRecord, WebhookReceiver
# Defensive Guards:   9 fail-closed invariants (zero external deps)

import hmac
import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Any


class ContractMismatchError(RuntimeError):
    """Raised when an inbound A2A webhook does not match its registration-time contract."""
    pass


class TaskState(Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    RECONCILING = "reconciling"
    COMPLETED = "completed"
    FAILED = "failed"


@dataclass
class PushContract:
    """The contract bound at tasks/pushNotificationConfig/set time."""
    schema: str
    auth_scheme: str
    hmac_key: bytes | None
    task_id_field: str
    state_field: str
    terminal_states: frozenset[str]


@dataclass
class TaskRecord:
    task_id: str
    state: TaskState
    contract: PushContract
    card_version_at_bind: str
    reconcile_attempts: int = 0


class WebhookReceiver:
    def __init__(self, records: dict[str, TaskRecord]):
        self._records = records

    def _validate_envelope(self, task_id: str, payload: dict[str, Any]) -> TaskState:
        record = self._records.get(task_id)
        if record is None:
            raise ContractMismatchError(f"no registration for task {task_id!r}")

        c = record.contract

        # 1. Schema envelope check against the REGISTRATION contract, not the live Card.
        if c.schema == "a2a.push.v1":
            if "notification" in payload:
                raise ContractMismatchError(
                    f"task {task_id}: v2 envelope arrived under v1 contract"
                )
            state_raw = payload.get(c.state_field)
            if not isinstance(state_raw, str):
                raise ContractMismatchError(
                    f"task {task_id}: state field {c.state_field!r} not a string"
                )
        elif c.schema == "a2a.push.v2":
            if "notification" not in payload:
                raise ContractMismatchError(
                    f"task {task_id}: expected v2 notification envelope"
                )
            state_raw = payload["notification"].get(c.state_field, {}).get("name")
            if not isinstance(state_raw, str):
                raise ContractMismatchError(
                    f"task {task_id}: v2 state.name missing or non-string"
                )
        else:
            raise ContractMismatchError(f"unknown bound schema {c.schema!r}")

        # 2. Auth scheme must match the bound scheme.
        if c.auth_scheme == "hmac-sha256" and c.hmac_key is not None:
            body = payload.get("_raw_body", b"")
            sig = payload.get("_signature", "")
            expected = hmac.new(c.hmac_key, body, hashlib.sha256).hexdigest()
            if not hmac.compare_digest(expected, sig):
                raise ContractMismatchError(f"task {task_id}: HMAC mismatch")

        # 3. Only transition on a well-formed state.
        try:
            return TaskState(state_raw)
        except ValueError as e:
            raise ContractMismatchError(
                f"task {task_id}: state {state_raw!r} not in lifecycle"
            ) from e

    def handle(self, task_id: str, payload: dict[str, Any]) -> int:
        record = self._records.get(task_id)
        if record is None:
            # Unknown task: 404, never 200. A 200 here is a silent loss.
            return 404
        try:
            new_state = self._validate_envelope(task_id, payload)
        except ContractMismatchError:
            # Do NOT swallow. Force the state machine into RECONCILING and
            # return a non-2xx so the server retries / dead-letters.
            record.state = TaskState.RECONCILING
            record.reconcile_attempts += 1
            if record.reconcile_attempts > 2:
                # Card-version pin exhausted: escalate, do not retry.
                raise ContractMismatchError(
                    f"task {task_id}: contract diverged beyond reconcile budget; "
                    f"pinned {record.card_version_at_bind}"
                )
            return 409

        # Validated: advance state machine.
        record.state = new_state
        record.reconcile_attempts = 0
        return 200
