# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-terminal-task-state-as-authoritative-when-its-own-push-notification-webhook-binding-has-drifted.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-terminal-task-state-as-authoritative-when-its-own-push-notification-webhook-binding-has-drifted.warrant.json
# Markdown SHA-256:   9d42a75a6de823b1312f5ca83772afde4f8ff5b10efb39a0276bc5995264ea0c
# Code AST SHA-256:   8d2ceec987315b6c9c91f2e291d843ee2c3869a7a5badb26b69315271e889ec8
# Verified Classes:   BindingDriftError, LocalState, TaskRecord, AgentCard
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class BindingDriftError(RuntimeError):
    """Raised when a terminal state cannot be reconciled from remote truth."""


class LocalState(Enum):
    WORKING = "working"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"
    INDETERMINATE = "indeterminate"


@dataclass
class TaskRecord:
    task_id: str
    binding_epoch: str
    submitted_at: float
    expected_duration: float
    last_confirmed_working: float
    state: LocalState = LocalState.WORKING
    webhook_rejections: int = 0
    retry_budget: float = 90.0


@dataclass
class AgentCard:
    binding_epoch: str
    callback_url: str


def reconcile(
    task: TaskRecord,
    current_card: AgentCard,
    fetch_remote_state,          # callable(task_id) -> Optional[str]
    now: Optional[float] = None,
) -> LocalState:
    now = now if now is not None else time.time()

    drift = current_card.binding_epoch != task.binding_epoch
    rejected = task.webhook_rejections > 0
    overdue = (now - task.last_confirmed_working) > task.expected_duration * 1.5
    retry_exhausted = (now - task.submitted_at) > task.retry_budget and rejected

    if not (drift or rejected or overdue or retry_exhausted):
        return task.state  # webhook-only path remains valid

    # Boundary crossed: webhook is no longer authoritative. Poll remote truth.
    remote = fetch_remote_state(task.task_id)

    if remote in ("completed", "failed", "canceled"):
        task.state = LocalState(remote)
        return task.state

    if remote == "working":
        # Remote still working; do NOT synthesize terminality from delivery failure.
        task.last_confirmed_working = now
        return LocalState.WORKING

    # Remote unreachable or unknown AND we have crossed the boundary.
    if overdue or retry_exhausted:
        task.state = LocalState.INDETERMINATE
        raise BindingDriftError(
            f"task {task.task_id}: cannot reconcile terminal state "
            f"(drift={drift}, rejections={task.webhook_rejections}, "
            f"overdue={overdue}, epoch_local={task.binding_epoch}, "
            f"epoch_remote={current_card.binding_epoch})"
        )

    return LocalState.INDETERMINATE
