# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-capability-advertisement-as-a-stale-lease-rather-than-a-durable-contract.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-capability-advertisement-as-a-stale-lease-rather-than-a-durable-contract.warrant.json
# Markdown SHA-256:   04400dd0011021f5e0dcb9a84dd578a99995c2d213f924750446bdfe0d09dcd9
# Code AST SHA-256:   7000977834cbbb01c9e010ee376b81cf33c24c9cbb45dc3946e0b18a02791008
# Verified Classes:   StaleCapabilityLeaseError, CapabilityManifest, LeaseCache
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Any


class StaleCapabilityLeaseError(RuntimeError):
    """Raised when a chained call would cross an unvalidated capability epoch boundary."""


@dataclass
class CapabilityManifest:
    peer_id: str
    epoch: int
    tools: dict[str, dict[str, Any]]
    issued_at: float
    ttl_seconds: float = 30.0


@dataclass
class LeaseCache:
    _store: dict[str, CapabilityManifest] = field(default_factory=dict)

    def put(self, manifest: CapabilityManifest) -> None:
        existing = self._store.get(manifest.peer_id)
        if existing is not None and manifest.epoch < existing.epoch:
            raise StaleCapabilityLeaseError(
                f"refusing to regress peer {manifest.peer_id} from epoch "
                f"{existing.epoch} to {manifest.epoch}"
            )
        self._store[manifest.peer_id] = manifest

    def get_for_chain(self, peer_id: str, now: float | None = None) -> CapabilityManifest:
        now = time.monotonic() if now is None else now
        manifest = self._store.get(peer_id)
        if manifest is None:
            raise StaleCapabilityLeaseError(f"no cached manifest for peer {peer_id}")
        if now - manifest.issued_at > manifest.ttl_seconds:
            raise StaleCapabilityLeaseError(
                f"lease for peer {peer_id} epoch {manifest.epoch} expired "
                f"({now - manifest.issued_at:.1f}s > {manifest.ttl_seconds}s); renegotiate"
            )
        return manifest


def build_chain(
    cache: LeaseCache,
    peer_id: str,
    tool_name: str,
    peer_current_epoch: int,
    now: float | None = None,
) -> dict[str, Any]:
    """Construct a chained call envelope, enforcing the lease invariant."""
    manifest = cache.get_for_chain(peer_id, now=now)
    if peer_current_epoch != manifest.epoch:
        raise StaleCapabilityLeaseError(
            f"peer {peer_id} is at epoch {peer_current_epoch} but cached lease is "
            f"epoch {manifest.epoch}; chaining would cross an unvalidated boundary"
        )
    if tool_name not in manifest.tools:
        raise StaleCapabilityLeaseError(
            f"tool {tool_name} absent from peer {peer_id} manifest at epoch {manifest.epoch}"
        )
    return {
        "peer_id": peer_id,
        "tool": tool_name,
        "epoch": manifest.epoch,
        "schema": manifest.tools[tool_name],
    }
