# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-re-issued-a2a-task-that-arrives-with-a-higher-revision-but-a-lower-task-epoch-and-why-vendor-card-cach.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-re-issued-a2a-task-that-arrives-with-a-higher-revision-but-a-lower-task-epoch-and-why-vendor-card-cach.warrant.json
# Markdown SHA-256:   bafbff08e90ee58a25d6ebd2c5fdbe18587c115cbf8f0ef9324b9b59e6f31b41
# Code AST SHA-256:   b91806c096526577876b03b8b3710a067f09d34a60fb8e1673f9140a96e8a2c8
# Verified Classes:   EpochMismatchError, TaskView
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class EpochMismatchError(RuntimeError):
    """Raised when a re-issued A2A task cannot be merged by revision ordering."""

    def __init__(self, task_id: str, incoming_epoch: Optional[int],
                 local_epoch: Optional[int], incoming_rev: int, local_rev: int):
        self.task_id = task_id
        self.incoming_epoch = incoming_epoch
        self.local_epoch = local_epoch
        self.incoming_rev = incoming_rev
        self.local_rev = local_rev
        super().__init__(
            f"task {task_id}: incoming epoch={incoming_epoch} rev={incoming_rev} "
            f"vs local epoch={local_epoch} rev={local_rev} — not mergeable by revision"
        )


@dataclass
class TaskView:
    task_id: str
    revision: int
    task_epoch: Optional[int]      # None == unknown / absent on the wire
    writer_id: str
    status: str                    # "submitted" | "working" | "input-required" | "completed"
    side_effects_emitted: bool     # true once any non-idempotent tool call has run


def may_merge_reissue(local: TaskView, incoming: TaskView,
                      card_cache_says_epochs: bool) -> bool:
    """
    Decide whether `incoming` may overwrite `local`.

    The epoch check runs UNCONDITIONALLY. `card_cache_says_epochs` only
    gates the optional warrant-verification sub-step; it must never be
    used to skip mismatch detection.
    """
    if incoming.task_id != local.task_id:
        raise EpochMismatchError(
            local.task_id, incoming.task_epoch, local.task_epoch,
            incoming.revision, local.revision,
        )

    # --- unconditional ownership check ---
    if incoming.task_epoch is None or local.task_epoch is None:
        # Unknown epoch is treated as mismatch whenever side effects exist.
        if local.side_effects_emitted or local.revision > 0:
            raise EpochMismatchError(
                local.task_id, incoming.task_epoch, local.task_epoch,
                incoming.revision, local.revision,
            )
        # No side effects yet: revision ordering is safe.
        return incoming.revision > local.revision

    if incoming.task_epoch != local.task_epoch:
        # Competing ownership claim, not a newer view.
        raise EpochMismatchError(
            local.task_id, incoming.task_epoch, local.task_epoch,
            incoming.revision, local.revision,
        )

    # Same epoch: revision ordering is valid, but writer identity must agree.
    if incoming.writer_id != local.writer_id:
        raise EpochMismatchError(
            local.task_id, incoming.task_epoch, local.task_epoch,
            incoming.revision, local.revision,
        )

    # Cached card flag is a hint only; it is NOT consulted for the
    # mismatch decision above. It may suppress warrant verification,
    # which is a separate step handled by the caller.
    _ = card_cache_says_epochs
    return incoming.revision > local.revision


def apply_reissue(local: TaskView, incoming: TaskView,
                  card_cache_says_epochs: bool) -> TaskView:
    if not may_merge_reissue(local, incoming, card_cache_says_epochs):
        # Caller must reconcile via state query, not by overwriting.
        raise EpochMismatchError(
            local.task_id, incoming.task_epoch, local.task_epoch,
            incoming.revision, local.revision,
        )
    return incoming
