# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-a2a-task-state-transition-as-authoritative-across-vendors-and-when-is-it-merely-advisory.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-a2a-task-state-transition-as-authoritative-across-vendors-and-when-is-it-merely-advisory.warrant.json
# Markdown SHA-256:   32c77c1559b1831368f568ebad4e01f02d8ed3f61ef20f654498d52198859562
# Code AST SHA-256:   a2ba0aa7231e945b44bc7b920e1c305f50c3fd80b40fb714ca1a0586b1cfc522
# Verified Classes:   StateAuthorityError, Authority, ObservedState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class StateAuthorityError(RuntimeError):
    """Raised when an observed A2A Task.state cannot be classified as
    authoritative and the caller attempted to act on it as if it were."""
    pass


class Authority(Enum):
    AUTHORITATIVE = "authoritative"        # terminal, final-frame or post-frame poll
    BLOCKING_DEMAND = "blocking_demand"    # input-required: must respond, must not wait
    INDETERMINATE = "indeterminate"        # working/submitted past silence bound, or stream closed w/o terminal


TERMINAL = {"completed", "failed", "canceled"}
NON_TERMINAL = {"submitted", "working", "input-required"}


@dataclass
class ObservedState:
    state: str
    final_frame: bool          # did a TaskStatusUpdateEvent with final:true arrive?
    stream_open: bool
    last_frame_ts: float
    now: float
    card_age_s: float
    card_freshness_bound_s: float


def classify(obs: ObservedState, max_silence_s: float = 90.0) -> Authority:
    if obs.state not in TERMINAL | NON_TERMINAL:
        raise StateAuthorityError(
            f"unknown A2A state {obs.state!r}; refusing to classify"
        )

    # Condition 1: terminal state is authoritative only with a final frame
    # or a post-frame poll (encoded here as final_frame=True).
    if obs.state in TERMINAL:
        if obs.final_frame:
            return Authority.AUTHORITATIVE
        # terminal state observed without final frame: could be a stale stream
        # replay or a poll; require explicit confirmation upstream.
        raise StateAuthorityError(
            f"terminal state {obs.state!r} observed without final:true frame; "
            "must be confirmed via tasks/get before releasing resources"
        )

    # input-required is a blocking demand, never a progress signal.
    if obs.state == "input-required":
        if obs.card_age_s > obs.card_freshness_bound_s:
            # payload schema may have drifted; treat as advisory until re-fetch
            raise StateAuthorityError(
                "input-required received but Agent Card is stale "
                f"({obs.card_age_s:.0f}s > {obs.card_freshness_bound_s:.0f}s); "
                "re-fetch card before validating clarification payload"
            )
        return Authority.BLOCKING_DEMAND

    # working / submitted
    silence = obs.now - obs.last_frame_ts
    if not obs.stream_open:
        # stream closed without terminal event -> indeterminate, not working
        return Authority.INDETERMINATE
    if silence > max_silence_s:
        return Authority.INDETERMINATE
    return Authority.INDETERMINATE  # non-terminal is never authoritative for release


def release_parent_step(obs: ObservedState) -> None:
    auth = classify(obs)
    if auth is not Authority.AUTHORITATIVE:
        raise StateAuthorityError(
            f"cannot release parent DAG step on state {obs.state!r} "
            f"with authority {auth.value}; resolve via tasks/get or tasks/cancel"
        )
    # ... release held resources, propagate to downstream vendor ...
