# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-an-a2a-v1-0-task-before-the-remote-agent-card-s-declared-capabilities-streaming-and-push-notification-config-are.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-an-a2a-v1-0-task-before-the-remote-agent-card-s-declared-capabilities-streaming-and-push-notification-config-are.warrant.json
# Markdown SHA-256:   0a3e8446ba7b38a6b2154dd162895dad03af93304fad4734089bb15d77231b6b
# Code AST SHA-256:   0fc0b54dcbfc3127959402a0126f160e36489d6b9e861235031d5a0ee7af1739
# Verified Classes:   A2ATransportDriftError, TaskState, AgentCard, TaskEnvelope, StreamObservation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class A2ATransportDriftError(RuntimeError):
    """Raised when the effective task transport diverges from the cached Agent Card
    and the client has no reconciliation path (tasks/get or push config)."""
    pass


class TaskState(Enum):
    PENDING = "pending"
    TRANSPORT_DEGRADED = "transport_degraded"
    COMPLETED = "completed"
    FAILED = "failed"


@dataclass
class AgentCard:
    streaming: bool
    push_notifications: bool
    fetched_at: float
    ttl: float = 3600.0

    def is_fresh(self, now: Optional[float] = None) -> bool:
        now = now if now is not None else time.time()
        return (now - self.fetched_at) <= self.ttl


@dataclass
class TaskEnvelope:
    task_id: str
    status_state: str  # "submitted" | "working" | "completed" | "failed"
    push_config_registered: bool = False


@dataclass
class StreamObservation:
    first_event_at: Optional[float] = None
    empty_stream: bool = False
    method_not_found: bool = False


def submit_and_observe(
    card: AgentCard,
    envelope: TaskEnvelope,
    observation: StreamObservation,
    first_event_budget_s: float = 15.0,
    now: Optional[float] = None,
) -> TaskState:
    """
    Decide the task's observation state after a message/stream submission.

    Invariant: a Task envelope with status 'submitted' is NOT evidence that the
    stream will carry events. Only an observed first event, or a successful
    tasks/get reconciliation, or a registered push config, makes the task
    observable. Otherwise we enter TRANSPORT_DEGRADED, never retry-submit.
    """
    now = now if now is not None else time.time()

    if not card.is_fresh(now):
        # Card is stale; we cannot trust its capability bits to bound the
        # observation channel. We must revalidate before relying on streaming.
        raise A2ATransportDriftError(
            f"Agent Card stale (age={now - card.fetched_at:.0f}s > ttl={card.ttl:.0f}s); "
            "revalidate before acting on capabilities.streaming"
        )

    # Case 1: server accepted task but stream is empty / method missing.
    if observation.method_not_found or observation.empty_stream:
        # The task is alive server-side; the observation channel is not.
        # We must NOT re-submit message/stream. We must reconcile.
        if card.push_notifications and not envelope.push_config_registered:
            # No push config => result will be orphaned. This is the hard failure.
            raise A2ATransportDriftError(
                f"task {envelope.task_id}: stream unavailable "
                f"(method_not_found={observation.method_not_found}, "
                f"empty_stream={observation.empty_stream}) and no push config "
                "registered; result will be orphaned. Register "
                "tasks/pushNotificationConfig/set before retrying."
            )
        return TaskState.TRANSPORT_DEGRADED

    # Case 2: no first event within budget, but stream did not explicitly fail.
    if observation.first_event_at is None:
        elapsed = now - _submission_time_placeholder(now)
        if elapsed > first_event_budget_s:
            # Silence is not failure. Switch to tasks/get polling.
            return TaskState.TRANSPORT_DEGRADED

    # Case 3: first event observed; task is observable via stream.
    if envelope.status_state == "completed":
        return TaskState.COMPLETED
    if envelope.status_state == "failed":
        return TaskState.FAILED
    return TaskState.PENDING


def _submission_time_placeholder(now: float) -> float:
    # In production this is the timestamp captured at message/stream send time;
    # the placeholder keeps the example self-contained.
    return now - 1.0


def reconcile_via_get(
    envelope: TaskEnvelope,
    tasks_get_result: Optional[dict],
) -> TaskState:
    """
    Reconcile a TRANSPORT_DEGRADED task via tasks/get. This is the only path
    that may transition a degraded task to COMPLETED or FAILED.
    """
    if tasks_get_result is None:
        # -32602 unknown task: the task never existed or was GC'd.
        raise A2ATransportDriftError(
            f"task {envelope.task_id}: tasks/get returned unknown task; "
            "cannot reconcile degraded transport"
        )
    state = tasks_get_result.get("status", {}).get("state")
    if state == "completed":
        return TaskState.COMPLETED
    if state in ("failed", "canceled"):
        return TaskState.FAILED
    return TaskState.TRANSPORT_DEGRADED
