# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-subject-identifiers-when-a-federated-peer-re-issues-an-aaif-warrant-under-a-rotated-issuer-key-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-subject-identifiers-when-a-federated-peer-re-issues-an-aaif-warrant-under-a-rotated-issuer-key-mid-handoff.warrant.json
# Markdown SHA-256:   37525d7a2e1a358b81a3a53279fe141c16d0289a61c760fef41a3d9f6213444f
# Code AST SHA-256:   aa9513b425c82b7a60f7f77a4c1d05c5676eb9731bbad47d34a0e569684200b3
# Verified Classes:   IdentityRebindError, EpochContinuity, Warrant, CachedResolution, FederatedResolver
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class IdentityRebindError(RuntimeError):
    """Raised when a subject resolution crosses an issuer-key epoch boundary
    that the issuer has not asserted as CONTINUED, and the caller attempted
    to merge attributes across that boundary."""


class EpochContinuity(Enum):
    CONTINUED = "continued"      # same principal, new signing key
    REASSIGNED = "reassigned"    # sub string reused for a new principal
    UNKNOWN = "unknown"          # issuer has not asserted; fail closed


@dataclass(frozen=True)
class Warrant:
    issuer: str
    sub: str
    kid: str
    epoch: int
    capabilities: frozenset[str]


@dataclass(frozen=True)
class CachedResolution:
    principal_id: str
    kid: str
    epoch: int
    capabilities: frozenset[str]


class FederatedResolver:
    def __init__(self) -> None:
        # Cache keyed on (issuer, sub, epoch) -- NOT (issuer, sub).
        self._cache: dict[tuple[str, str, int], CachedResolution] = {}
        # Issuer-published epoch-continuity assertions, keyed (issuer, sub, from_epoch).
        self._continuity: dict[tuple[str, str, int], EpochContinuity] = {}

    def register_continuity(
        self, issuer: str, sub: str, from_epoch: int, state: EpochContinuity
    ) -> None:
        self._continuity[(issuer, sub, from_epoch)] = state

    def resolve(self, w: Warrant, merge_attributes: bool) -> CachedResolution:
        key = (w.issuer, w.sub, w.epoch)
        cached = self._cache.get(key)
        if cached is not None and cached.kid == w.kid:
            return cached

        # Look for a prior-epoch resolution of the same (issuer, sub).
        prior: Optional[CachedResolution] = None
        prior_epoch = -1
        for (iss, sub, ep), res in self._cache.items():
            if iss == w.issuer and sub == w.sub and ep < w.epoch and ep > prior_epoch:
                prior, prior_epoch = res, ep

        if prior is not None:
            state = self._continuity.get((w.issuer, w.sub, prior_epoch), EpochContinuity.UNKNOWN)
            if state is EpochContinuity.REASSIGNED and merge_attributes:
                raise IdentityRebindError(
                    f"refusing attribute merge across REASSIGNED epoch boundary: "
                    f"issuer={w.issuer} sub={w.sub} "
                    f"prior_epoch={prior_epoch}(kid={prior.kid}) -> "
                    f"epoch={w.epoch}(kid={w.kid}); "
                    f"capabilities must be re-derived from current warrant instance only"
                )
            if state is EpochContinuity.UNKNOWN and merge_attributes:
                raise IdentityRebindError(
                    f"fail-closed: issuer has not asserted continuity for "
                    f"issuer={w.issuer} sub={w.sub} epoch {prior_epoch}->{w.epoch}; "
                    f"attribute merge denied pending issuer epoch-continuity assertion"
                )

        resolution = CachedResolution(
            principal_id=f"{w.issuer}:{w.sub}:e{w.epoch}",
            kid=w.kid,
            epoch=w.epoch,
            capabilities=w.capabilities,
        )
        self._cache[key] = resolution
        return resolution
