# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-asymmetric-trust-anchor-expiry-during-cross-org-capability-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-asymmetric-trust-anchor-expiry-during-cross-org-capability-negotiation.warrant.json
# Markdown SHA-256:   b51b4153d3a51a17f18726e490664fab17df803e77486d16dfd966e62a914bb8
# Code AST SHA-256:   76c53dc03462e15be317c1f2571de251c1aa300bdcb87dc4ef529446cd678c1b
# Verified Classes:   TrustReconciliationError, Anchor, SessionGrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass


class TrustReconciliationError(RuntimeError):
    """Raised when a federated capability cannot be soundly reconciled
    against the verifier's trust anchor at invocation time."""


@dataclass(frozen=True)
class Anchor:
    anchor_id: str
    not_after: float  # epoch seconds, verifier's reference clock


@dataclass(frozen=True)
class SessionGrant:
    manifest_id: str
    bound_anchor_id: str
    bound_anchor_version: int
    session_ttl: float


SKEW_BOUND = 5.0  # seconds; |clock_alpha - clock_beta| must not exceed this


def reconcile_invocation(
    grant: SessionGrant,
    chain: list[Anchor],
    resolved_anchor: Anchor,
    resolved_anchor_version: int,
    now: float,
    peer_clock_offset: float,
) -> str:
    """Decide proceed / re-anchor / refuse for one privileged invocation.

    Returns one of: "proceed", "re_anchor".
    Raises TrustReconciliationError with a typed reason otherwise.
    """
    if abs(peer_clock_offset) > SKEW_BOUND:
        # Cannot trust any expiry comparison; fail closed, do not guess.
        raise TrustReconciliationError(
            f"clock_skew_exceeded: offset={peer_clock_offset:.2f}s "
            f"> bound={SKEW_BOUND}s"
        )

    # The governing lifetime is the MINIMUM remaining across the whole chain,
    # not the leaf manifest's own expiry.
    remaining = min(a.not_after - now for a in chain)
    if remaining <= 0.0:
        # Distinguish expiry from unreachability for the peer's retry policy.
        raise TrustReconciliationError(
            f"anchor_expired: governing_anchor={resolved_anchor.anchor_id} "
            f"expired {-remaining:.1f}s ago; re-presenting same chain is futile"
        )

    if resolved_anchor.anchor_id != grant.bound_anchor_id:
        raise TrustReconciliationError(
            f"anchor_mismatch: grant bound to {grant.bound_anchor_id}, "
            f"resolved {resolved_anchor.anchor_id}"
        )

    if resolved_anchor_version != grant.bound_anchor_version:
        # Anchor rotated but is live: preserve state, force a bounded re-anchor.
        return "re_anchor"

    if grant.session_ttl > remaining - SKEW_BOUND:
        # Session would outlive its anchoring trust; must be renegotiated.
        raise TrustReconciliationError(
            f"session_outlives_anchor: ttl={grant.session_ttl:.1f}s "
            f"exceeds remaining_minus_skew={remaining - SKEW_BOUND:.1f}s"
        )

    return "proceed"
