# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-task-from-a-stale-agent-card-and-then-lose-the-result-at-the-webhook-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-task-from-a-stale-agent-card-and-then-lose-the-result-at-the-webhook-boundary.warrant.json
# Markdown SHA-256:   70357abff7fa196eeae92fc9e9dd52bd3f047cdf3cce83f052433e78ca98b108
# Code AST SHA-256:   fb73e2cd25927839264adc68e0a465607ad43422cf05634dddf42d349dad5e7a
# Verified Classes:   ContractSkewError, CardCacheExpiredError, AgentCard, TaskRecord, NotificationEnvelope, A2AClient
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Optional


class ContractSkewError(RuntimeError):
    """Raised when a push notification's envelope does not match the
    Agent Card version under which the task was submitted."""
    pass


class CardCacheExpiredError(RuntimeError):
    """Raised when a task submission is attempted against a card whose
    cache TTL has elapsed and no re-fetch has occurred."""
    pass


@dataclass
class AgentCard:
    version: str
    webhook_url: str
    auth_scheme: str
    skill_ids: list[str]
    fetched_at: datetime
    ttl: timedelta = timedelta(hours=24)

    def is_expired(self, now: Optional[datetime] = None) -> bool:
        now = now or datetime.utcnow()
        return now - self.fetched_at > self.ttl

    def fingerprint(self) -> str:
        payload = json.dumps(
            {
                "version": self.version,
                "webhook_url": self.webhook_url,
                "auth_scheme": self.auth_scheme,
                "skill_ids": sorted(self.skill_ids),
            },
            sort_keys=True,
        ).encode()
        return hashlib.sha256(payload).hexdigest()[:16]


@dataclass
class TaskRecord:
    task_id: str
    skill_id: str
    submitted_under_card_fingerprint: str
    state: str = "submitted"
    terminal_confirmed: bool = False


@dataclass
class NotificationEnvelope:
    task_id: str
    event: str
    auth_scheme: str
    payload: dict
    card_fingerprint_echo: Optional[str] = None


class A2AClient:
    def __init__(self, card: AgentCard):
        self.card = card
        self.tasks: dict[str, TaskRecord] = {}

    def submit_task(self, task_id: str, skill_id: str) -> TaskRecord:
        if self.card.is_expired():
            raise CardCacheExpiredError(
                f"Agent Card {self.card.version} cache expired at "
                f"{self.card.fetched_at + self.card.ttl}; re-fetch required "
                f"before submitting task {task_id}"
            )
        if skill_id not in self.card.skill_ids:
            raise ContractSkewError(
                f"Skill {skill_id} not advertised in cached card "
                f"{self.card.version} (fingerprint {self.card.fingerprint()})"
            )
        record = TaskRecord(
            task_id=task_id,
            skill_id=skill_id,
            submitted_under_card_fingerprint=self.card.fingerprint(),
        )
        self.tasks[task_id] = record
        return record

    def receive_notification(self, envelope: NotificationEnvelope) -> TaskRecord:
        record = self.tasks.get(envelope.task_id)
        if record is None:
            raise ContractSkewError(
                f"Notification for unknown task {envelope.task_id}; "
                f"possible cross-task mis-binding after card redeploy"
            )

        # Invariant: the notification must be verifiable against the
        # contract under which the task was submitted.
        if envelope.auth_scheme != self.card.auth_scheme:
            raise ContractSkewError(
                f"Auth scheme skew for task {envelope.task_id}: "
                f"notification uses {envelope.auth_scheme!r}, cached card "
                f"{self.card.version} declares {self.card.auth_scheme!r}. "
                f"Do not retry against the stale card; re-fetch and reconcile "
                f"via tasks/get."
            )

        if (
            envelope.card_fingerprint_echo is not None
            and envelope.card_fingerprint_echo != record.submitted_under_card_fingerprint
        ):
            raise ContractSkewError(
                f"Card fingerprint mismatch for task {envelope.task_id}: "
                f"task submitted under {record.submitted_under_card_fingerprint}, "
                f"notification echoes {envelope.card_fingerprint_echo}. "
                f"Task state on server is authoritative; reconcile via tasks/get."
            )

        if envelope.event == "completed":
            record.state = "completed"
            record.terminal_confirmed = True
        return record


def reconcile_via_poll(client: A2AClient, task_id: str, server_state: str) -> TaskRecord:
    """Fallback path when push notification is lost or rejected.

    Called only after a ContractSkewError has been raised and the card
    has been re-fetched. The server's tasks/get response is authoritative.
    """
    record = client.tasks.get(task_id)
    if record is None:
        raise ContractSkewError(
            f"Cannot reconcile unknown task {task_id}; task was never "
            f"submitted under a card this client holds"
        )
    if record.terminal_confirmed:
        return record
    if server_state in ("completed", "failed", "canceled"):
        record.state = server_state
        record.terminal_confirmed = True
    return record
