# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-policy-rejected-from-policy-not-yet-negotiated-in-cross-org-multi-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-policy-rejected-from-policy-not-yet-negotiated-in-cross-org-multi-agent-federation.warrant.json
# Markdown SHA-256:   ca982a8807d9583f46791842beefafe1cb60cbb51b340fb1b3ddeda2cbe82295
# Code AST SHA-256:   4f74eb33a4c20cb823188a1b73fa1e0c74701bb41f01a26407974a4d4464a908
# Verified Classes:   FederationPolicyError, Verdict, DenyResponse
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum


class FederationPolicyError(RuntimeError):
    """Raised when a federated 403 cannot be safely classified."""


class Verdict(Enum):
    IDENTITY_REJECTION = "identity_rejection"   # terminal, no retry
    NEGOTIATION_INCOMPLETE = "negotiation_incomplete"  # retry-safe
    GENUINE_DENIAL = "genuine_denial"           # terminal for action
    LOCAL_STALE = "local_stale"                 # refresh broker epoch


@dataclass(frozen=True)
class DenyResponse:
    status: int
    body: dict


def classify_federation_deny(
    resp: DenyResponse,
    local_epoch: int,
) -> Verdict:
    if resp.status != 403:
        raise FederationPolicyError(
            f"classifier only handles 403, got {resp.status}"
        )
    epoch = resp.body.get("epoch")
    if epoch is None:
        # No negotiation epoch echoed: identity gate failed. Terminal.
        return Verdict.IDENTITY_REJECTION
    if not isinstance(epoch, int):
        raise FederationPolicyError(
            f"epoch must be int, got {type(epoch).__name__}={epoch!r}"
        )
    if epoch < local_epoch:
        return Verdict.NEGOTIATION_INCOMPLETE
    if epoch == local_epoch:
        return Verdict.GENUINE_DENIAL
    return Verdict.LOCAL_STALE


def handle_federated_call(resp: DenyResponse, local_epoch: int) -> str:
    verdict = classify_federation_deny(resp, local_epoch)
    if verdict is Verdict.NEGOTIATION_INCOMPLETE:
        return "retry_with_backoff"
    if verdict is Verdict.LOCAL_STALE:
        return "refresh_epoch_then_redecide"
    if verdict is Verdict.IDENTITY_REJECTION:
        raise FederationPolicyError(
            "identity rejection: no negotiation epoch in 403 body; "
            "do not retry against same broker"
        )
    if verdict is Verdict.GENUINE_DENIAL:
        raise FederationPolicyError(
            f"genuine policy denial at epoch {local_epoch}; escalate to policy owner"
        )
    raise FederationPolicyError(f"unhandled verdict {verdict!r}")
