# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-partially-materialized-a2a-v1-0-task-as-terminal-when-agent-card-discovery-succeeds-but-the-task-state-transition-graph.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-partially-materialized-a2a-v1-0-task-as-terminal-when-agent-card-discovery-succeeds-but-the-task-state-transition-graph.warrant.json
# Markdown SHA-256:   853a59eea61e17d63af9f24734bc648d0360763a08e12602ca883485114cc204
# Code AST SHA-256:   c968a06d2e771739cc72328438a77822d119d55ead03334d26ea6484f74549b8
# Verified Classes:   TaskStateConformanceError, FalseTerminalError, AgentCard, TaskRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Callable, Optional

# A2A v1.0 closed universe of task states.
NON_TERMINAL = frozenset({"submitted", "working", "input-required"})
TERMINAL = frozenset({"completed", "failed", "canceled"})
LEGAL_STATES = NON_TERMINAL | TERMINAL


class TaskStateConformanceError(RuntimeError):
    """Raised when the remote emits a state outside the A2A v1.0 closed universe,
    or when a client attempts to record a terminal state not justified by the remote."""
    pass


class FalseTerminalError(TaskStateConformanceError):
    """Raised when a client would mark a task terminal while the remote is non-terminal."""
    pass


@dataclass
class AgentCard:
    streaming: bool
    push_notifications: bool
    # NOTE: does NOT enumerate states. Reachability is runtime-discovered.


@dataclass
class TaskRecord:
    task_id: str
    local_state: str = "submitted"
    remote_state: Optional[str] = None
    history: list = field(default_factory=list)


def poll_once(fetch: Callable[[str], dict], record: TaskRecord) -> str:
    """One tasks/get round. Returns the remote state after validating conformance."""
    resp = fetch(record.task_id)
    state = resp.get("status", {}).get("state")
    if state not in LEGAL_STATES:
        raise TaskStateConformanceError(
            f"remote emitted illegal state {state!r} for task {record.task_id}; "
            f"legal set is {sorted(LEGAL_STATES)}"
        )
    record.remote_state = state
    record.history.append(state)
    return state


def drive_task(
    fetch: Callable[[str], dict],
    record: TaskRecord,
    card: AgentCard,
    remote_ttl_s: float,
    on_input_required: Callable[[str], Optional[dict]],
    resume: Callable[[str, dict], None],
    cancel: Callable[[str], None],
) -> str:
    """Drive a task to a justified terminal state. Never returns a false terminal."""
    poll_interval = 5.0 if card.push_notifications else min(remote_ttl_s / 3.0, 5.0)
    deadline = time.monotonic() + remote_ttl_s

    while time.monotonic() < deadline:
        state = poll_once(fetch, record)

        if state in TERMINAL:
            record.local_state = state
            return state

        if state == "input-required":
            payload = on_input_required(record.task_id)
            if payload is None:
                # Cannot obtain input in time: cancel, do NOT mark failed.
                cancel(record.task_id)
                record.local_state = "canceled"
                return "canceled"
            resume(record.task_id, payload)
            # fall through to continue polling

        time.sleep(poll_interval)

    # TTL expired while remote was non-terminal: cancel to force agreement.
    cancel(record.task_id)
    record.local_state = "canceled"
    return "canceled"


def assert_local_terminal_justified(record: TaskRecord) -> None:
    """Invariant guard: local terminal must match remote terminal, or be a recorded cancel."""
    if record.local_state in TERMINAL and record.remote_state not in TERMINAL:
        if record.local_state != "canceled":
            raise FalseTerminalError(
                f"task {record.task_id}: local={record.local_state!r} but "
                f"remote={record.remote_state!r}; only 'canceled' may diverge from a "
                f"non-terminal remote, and only after an explicit tasks/cancel."
            )
