# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-org-agent-trust-federation-from-silently-degrading-when-a-verifiable-presentation-s-credential-subject-diverges-from-th.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-org-agent-trust-federation-from-silently-degrading-when-a-verifiable-presentation-s-credential-subject-diverges-from-th.warrant.json
# Markdown SHA-256:   8ca64f24c802dc859d3b66f2b6fe5f8de5d4fbe1cf23cd13c0f70dcfd190c438
# Code AST SHA-256:   a84e943b4334b3b7515410bd7edef1a2ee59d9e10b06d7f12590e0e5b4719e49
# Verified Classes:   SubjectBindingError, Delegation, Credential, Manifest
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SubjectBindingError(RuntimeError):
    """Raised when a credential's subject cannot be soundly bound to the
    manifest agent — i.e., the delegation chain is broken, unscoped,
    expired, revoked, cyclic, or absent."""
    pass


@dataclass(frozen=True)
class Delegation:
    issuer: str
    subject: str
    scope: frozenset
    not_before: float
    not_after: float
    revoked: bool = False


@dataclass(frozen=True)
class Credential:
    subject_id: str
    scope: frozenset


@dataclass(frozen=True)
class Manifest:
    agent_id: str
    capabilities: frozenset


MAX_CHAIN_DEPTH = 4


def verify_subject_binding(
    manifest: Manifest,
    credential: Credential,
    delegations: list[Delegation],
    now: float,
) -> str:
    """Return 'equality' or the chain hash if binding is sound; raise
    SubjectBindingError otherwise. This is the invariant gate that naive
    pipelines omit."""
    if credential.subject_id == manifest.agent_id:
        return "equality"

    # Walk from credential subject toward manifest agent.
    current = credential.subject_id
    visited: set[str] = {current}
    chain: list[Delegation] = []

    for _ in range(MAX_CHAIN_DEPTH):
        hop = next(
            (d for d in delegations if d.issuer == current), None
        )
        if hop is None:
            raise SubjectBindingError(
                f"no delegation from {current!r} toward "
                f"{manifest.agent_id!r}; credential subject "
                f"{credential.subject_id!r} is unbound"
            )
        if hop.subject in visited:
            raise SubjectBindingError(
                f"delegation cycle detected at {hop.subject!r}"
            )
        if hop.revoked:
            raise SubjectBindingError(
                f"delegation {hop.issuer!r}->{hop.subject!r} revoked"
            )
        if not (hop.not_before <= now <= hop.not_after):
            raise SubjectBindingError(
                f"delegation {hop.issuer!r}->{hop.subject!r} outside "
                f"validity window [{hop.not_before}, {hop.not_after}]"
            )
        # Leaf credential's scope must be covered by EVERY hop.
        if not credential.scope.issubset(hop.scope):
            raise SubjectBindingError(
                f"delegation {hop.issuer!r}->{hop.subject!r} scope "
                f"{sorted(hop.scope)} does not cover credential scope "
                f"{sorted(credential.scope)}"
            )
        chain.append(hop)
        visited.add(hop.subject)
        current = hop.subject
        if current == manifest.agent_id:
            return "chain:" + "|".join(
                f"{d.issuer}->{d.subject}" for d in chain
            )

    raise SubjectBindingError(
        f"delegation chain exceeded max depth {MAX_CHAIN_DEPTH} "
        f"without reaching {manifest.agent_id!r}"
    )


def authorize(
    manifest: Manifest,
    credential: Credential,
    delegations: list[Delegation],
    now: float,
) -> dict:
    witness = verify_subject_binding(manifest, credential, delegations, now)
    if not credential.scope.issubset(manifest.capabilities):
        raise SubjectBindingError(
            f"credential scope {sorted(credential.scope)} exceeds "
            f"manifest capabilities {sorted(manifest.capabilities)}"
        )
    return {
        "principal": manifest.agent_id,
        "witness": witness,
        "granted_scope": sorted(credential.scope),
    }
