# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-peer-s-a2a-agent-card-that-advertises-tasks-resubscribe-support-but-silently-drops-the-sse-stream-after-input-requi.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-peer-s-a2a-agent-card-that-advertises-tasks-resubscribe-support-but-silently-drops-the-sse-stream-after-input-requi.warrant.json
# Markdown SHA-256:   31cffc3ceef380cf260abf001f256c2cddafa5158dcef4b33526bb070d51a6a2
# Code AST SHA-256:   d5770b3506c123eb133715251d2405a0cd934bfd319c798efa1af91e1f74e134
# Verified Classes:   A2AReattachViolation
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class A2AReattachViolation(RuntimeError):
    """Raised when a client attempts a write-bearing reattach without first
    reconciling remote task state via tasks/get, or when the remote card
    advertises resubscribe without replay guarantees and the client proceeds
    anyway."""
    pass


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


def reattach(
    card: dict,
    task_id: str,
    context_id: str,
    last_local_state: str,
    last_event_id: str | None,
    remote_get,
    remote_resubscribe,
    remote_send,
    pending_continuation: dict | None,
):
    streaming = card.get("capabilities", {}).get("streaming", False)
    history = card.get("capabilities", {}).get("stateTransitionHistory", False)

    if last_local_state in TERMINAL_STATES:
        raise A2AReattachViolation(
            f"reattach called on terminal state {last_local_state!r} for task {task_id}"
        )

    # Invariant: reattach is read-first. Never write before reconciling.
    remote_state = remote_get(task_id=task_id, context_id=context_id)
    if remote_state["taskId"] != task_id or remote_state["contextId"] != context_id:
        raise A2AReattachViolation(
            f"identity mismatch: expected ({task_id},{context_id}), "
            f"got ({remote_state['taskId']},{remote_state['contextId']})"
        )

    if remote_state["state"] in TERMINAL_STATES:
        # Task finished while we were disconnected; do not send continuation.
        return {"action": "reconcile_terminal", "state": remote_state["state"]}

    if remote_state["state"] != last_local_state:
        if not history:
            raise A2AReattachViolation(
                f"remote advanced {last_local_state!r}->{remote_state['state']!r} "
                f"but card lacks stateTransitionHistory; cannot replay safely"
            )
        # Replay missing transitions before any write.
        for t in remote_state.get("transitions", []):
            if t["from"] == last_local_state and t["to"] == remote_state["state"]:
                break
        else:
            raise A2AReattachViolation(
                f"no transition path {last_local_state!r}->{remote_state['state']!r}"
            )

    # Only now, with reconciled state, may we resubscribe (read) or send (write).
    if pending_continuation is not None:
        if remote_state["state"] not in {"input-required", "working"}:
            raise A2AReattachViolation(
                f"continuation not accepted in remote state {remote_state['state']!r}"
            )
        if not streaming:
            raise A2AReattachViolation(
                "continuation requires streaming but card does not advertise it"
            )
        return {"action": "send", "call": remote_send, "args": pending_continuation}

    if not streaming:
        raise A2AReattachViolation(
            "resubscribe requested but card does not advertise streaming"
        )
    # Resubscribe is read-only; attach cursor if we have one. If we do not and
    # the card lacks history, we must not assume the stream will replay.
    if last_event_id is None and not history:
        return {"action": "poll_get", "call": remote_get}
    return {"action": "resubscribe", "call": remote_resubscribe,
            "args": {"taskId": task_id, "lastEventId": last_event_id}}
