# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-cross-org-federation-policy-engine-silently-widen-a-delegated-capability-when-a-peer-s-audit-trail-reconciliation-clock-drif.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-cross-org-federation-policy-engine-silently-widen-a-delegated-capability-when-a-peer-s-audit-trail-reconciliation-clock-drif.warrant.json
# Markdown SHA-256:   a5e8846f321c950cb2c897dbdb99e0f35d135472b354d4b6b114f59c22250a70
# Code AST SHA-256:   41508aa6b44690e7900b1624a4327529bcf0df0176aee87db4130eb3a8394ec0
# Verified Classes:   FederationReconciliationError, GrantEvent, RevocationEvent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable


class FederationReconciliationError(RuntimeError):
    """Raised when a peer audit trail cannot be reconciled without widening a capability."""


@dataclass(frozen=True)
class GrantEvent:
    grant_id: str
    issuer: str
    subject: str
    resource: str
    verb: str
    not_before: int
    not_after: int
    event_time: int
    sequence: int  # peer-assigned monotonic emission sequence


@dataclass(frozen=True)
class RevocationEvent:
    grant_id: str
    event_time: int
    sequence: int


def reconcile(
    local_grants: dict[str, GrantEvent],
    local_revocations: dict[str, RevocationEvent],
    peer_events: Iterable[GrantEvent | RevocationEvent],
    peer_high_water: int,
) -> tuple[dict[str, GrantEvent], dict[str, RevocationEvent], int]:
    """
    Merge a peer's audit trail into local state.

    Invariants enforced:
      - A grant whose (not_before, not_after) differs from an already-known
        grant with the same grant_id is a CONFLICT, never a new instance.
      - A revocation targeting a known grant_id is never dropped because a
        replayed grant carries a later not_after.
      - Events below the peer's high-water sequence are rejected as replays.
    """
    grants = dict(local_grants)
    revocations = dict(local_revocations)
    new_high_water = peer_high_water

    for event in peer_events:
        if event.sequence <= peer_high_water:
            # Replay below the high-water mark: reject, do not re-baseline.
            continue

        if isinstance(event, GrantEvent):
            existing = grants.get(event.grant_id)
            if existing is not None and (
                existing.not_before != event.not_before
                or existing.not_after != event.not_after
            ):
                raise FederationReconciliationError(
                    f"peer {event.issuer} replayed grant {event.grant_id} with a "
                    f"changed validity window ({existing.not_before}..{existing.not_after} "
                    f"-> {event.not_before}..{event.not_after}); refusing to merge, "
                    f"capability would be resurrected past revocation"
                )
            grants[event.grant_id] = event
        elif isinstance(event, RevocationEvent):
            target = grants.get(event.grant_id)
            if target is None:
                # Revocation for an unknown grant: hold it, do not discard.
                revocations[event.grant_id] = event
            else:
                revocations[event.grant_id] = event
        else:
            raise FederationReconciliationError(
                f"unknown event type {type(event).__name__}"
            )

        new_high_water = max(new_high_water, event.sequence)

    # Cross-check: every revocation must target a known grant, and no live
    # grant may have a revocation whose event_time precedes its not_before.
    for grant_id, rev in revocations.items():
        grant = grants.get(grant_id)
        if grant is None:
            raise FederationReconciliationError(
                f"revocation for unknown grant {grant_id}; quarantine required"
            )
        if rev.event_time < grant.not_before:
            raise FederationReconciliationError(
                f"revocation {grant_id} precedes grant not_before; "
                f"clock fault suspected, refusing to clear"
            )

    return grants, revocations, new_high_water


def is_live(grant: GrantEvent, revocations: dict[str, RevocationEvent], now: int) -> bool:
    if not (grant.not_before <= now < grant.not_after):
        return False
    rev = revocations.get(grant.grant_id)
    if rev is not None and rev.event_time <= now:
        return False
    return True
