# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-in-a-federated-agent-mesh-silently-downgrade-to-a-weaker-peer-policy-after-a-single-renegotiation-round-trip-and-how-do-we-make-c.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a-federated-agent-mesh-silently-downgrade-to-a-weaker-peer-policy-after-a-single-renegotiation-round-trip-and-how-do-we-make-c.warrant.json
# Markdown SHA-256:   2dc4e123f8a6c1aaf5a1486a0863162ea59dbf6333dcab5054693badb7e9a4f6
# Code AST SHA-256:   0022c2c34f4ccc7355f714042d71f37fcc021c9d94b604662977a693f60c6253
# Verified Classes:   WarrantFoldError, Tri, Dim, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class WarrantFoldError(RuntimeError):
    """Raised when a warrant fold is not a meet (widening or incomparable)."""
    pass


class Tri(Enum):
    SET = "set"
    UNCONSTRAINED = "unconstrained"
    UNSPECIFIED = "unspecified"  # folds as bottom, NEVER as unconstrained


@dataclass(frozen=True)
class Dim:
    kind: Tri
    value: Optional[frozenset] = None

    def is_bottom(self) -> bool:
        return self.kind is Tri.UNSPECIFIED


@dataclass
class Warrant:
    dims: dict = field(default_factory=dict)  # name -> Dim


def fold(origin: Warrant, returned: Warrant) -> Warrant:
    """Intersect origin with a returned grant. Must be a meet, or raise."""
    out = Warrant()
    names = set(origin.dims) | set(returned.dims)
    for name in names:
        a = origin.dims.get(name, Dim(Tri.UNSPECIFIED))
        b = returned.dims.get(name, Dim(Tri.UNSPECIFIED))

        # UNSPECIFIED is bottom: it can only ever restrict, never widen.
        if a.is_bottom() or b.is_bottom():
            out.dims[name] = Dim(Tri.SET, frozenset())
            continue

        if a.kind is Tri.UNCONSTRAINED and b.kind is Tri.UNCONSTRAINED:
            out.dims[name] = Dim(Tri.UNCONSTRAINED)
            continue
        if a.kind is Tri.UNCONSTRAINED:
            out.dims[name] = b
            continue
        if b.kind is Tri.UNCONSTRAINED:
            out.dims[name] = a
            continue

        # Both SET: require comparable universes, then intersect.
        if getattr(a.value, "universe_id", None) != getattr(b.value, "universe_id", None):
            raise WarrantFoldError(
                f"dimension '{name}' has incomparable resource universes; "
                f"refusing to fold (would be a silent snapshot mismatch)"
            )
        inter = a.value & b.value
        out.dims[name] = Dim(Tri.SET, inter)

    # Post-condition: result must be <= origin in every dimension.
    for name, got in out.dims.items():
        want = origin.dims.get(name, Dim(Tri.UNSPECIFIED))
        if not _le(got, want):
            raise WarrantFoldError(
                f"fold widened dimension '{name}': got {got} not <= {want}"
            )
    return out


def _le(x: Dim, y: Dim) -> bool:
    if y.kind is Tri.UNCONSTRAINED:
        return True
    if x.kind is Tri.UNCONSTRAINED:
        return False
    if x.is_bottom():
        return True
    if y.is_bottom():
        return False
    return x.value <= y.value


def renegotiate(origin: Warrant, returned: Warrant) -> Warrant:
    try:
        return fold(origin, returned)
    except WarrantFoldError:
        raise
    except Exception as e:  # noqa: BLE001
        raise WarrantFoldError(f"unexpected fold failure: {e}") from e
