# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-trusted-agent-fail-to-bootstrap-trust-across-organizational-boundaries-when-its-attestation-chain-is-cryptographically-valid.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-trusted-agent-fail-to-bootstrap-trust-across-organizational-boundaries-when-its-attestation-chain-is-cryptographically-valid.warrant.json
# Markdown SHA-256:   c34c555d4baeb0303d6bd63d190d8d12479cef9ae4401a1cf6effe2fd3d1ff45
# Code AST SHA-256:   849508f5ec3fea4d0b3b45b13b49370fe994f1cc16a23de51674d65587de6363
# Verified Classes:   TrustBootstrapError, TrustAnchor, PresentedChain, Reason
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class TrustBootstrapError(RuntimeError):
    """Raised when cross-org agent trust cannot be bootstrapped.

    The `reason` field is part of the contract: callers MUST branch on it,
    not on the message string. Retrying is only legitimate for
    ANCHOR_EXPIRED (bounded, jittered); every other reason is terminal for
    the current attempt and must be escalated or failed closed.
    """

    class Reason(Enum):
        ANCHOR_MISSING = "anchor_missing"
        ANCHOR_SCOPE_MISMATCH = "anchor_scope_mismatch"
        ANCHOR_EXPIRED = "anchor_expired"
        DEPTH_EXCEEDED = "depth_exceeded"
        SIGNATURE_INVALID = "signature_invalid"

    def __init__(self, reason: "TrustBootstrapError.Reason", detail: str):
        self.reason = reason
        self.detail = detail
        super().__init__(f"{reason.value}: {detail}")


@dataclass(frozen=True)
class TrustAnchor:
    issuer: str            # canonicalized, e.g. "spiffe://org-a.example"
    scope_glob: str        # e.g. "spiffe://org-a.example/agent/*"
    max_delegation_depth: int
    active: bool


@dataclass(frozen=True)
class PresentedChain:
    root_issuer: str
    leaf_id: str
    delegation_depth: int
    signature_valid: bool


def _canonicalize(spiffe_id: str) -> str:
    # Normalize trailing slash, scheme case, and default port so that
    # byte-equality on anchors is meaningful. This is a common silent
    # source of ANCHOR_MISSING despite a "matching" anchor existing.
    s = spiffe_id.strip().rstrip("/")
    if s.startswith("SPIFFE://"):
        s = "spiffe://" + s[len("SPIFFE://"):]
    return s


def _glob_matches(glob: str, identity: str) -> bool:
    # Minimal single-`*` glob; real impls should use a vetted matcher.
    if not glob.endswith("*"):
        return glob == identity
    return identity.startswith(glob[:-1])


def bootstrap_trust(
    chain: PresentedChain,
    anchors: list[TrustAnchor],
) -> TrustAnchor:
    """Verify a presented attestation chain against the local policy graph.

    Returns the matching anchor on success. Raises TrustBootstrapError with a
    machine-branchable `reason` on every failure mode.
    """
    if not chain.signature_valid:
        raise TrustBootstrapError(
            TrustBootstrapError.Reason.SIGNATURE_INVALID,
            f"chain for {chain.leaf_id} failed signature verification",
        )

    root = _canonicalize(chain.root_issuer)
    candidates = [a for a in anchors if _canonicalize(a.issuer) == root]

    if not candidates:
        raise TrustBootstrapError(
            TrustBootstrapError.Reason.ANCHOR_MISSING,
            f"no trust anchor for issuer {root!r}; "
            f"this is a policy-graph provisioning gap, not a crypto failure",
        )

    scoped = [a for a in candidates if _glob_matches(a.scope_glob, _canonicalize(chain.leaf_id))]
    if not scoped:
        raise TrustBootstrapError(
            TrustBootstrapError.Reason.ANCHOR_SCOPE_MISMATCH,
            f"anchor for {root!r} exists but none covers leaf {chain.leaf_id!r}; "
            f"candidate scopes: {[a.scope_glob for a in candidates]}",
        )

    active = [a for a in scoped if a.active]
    if not active:
        raise TrustBootstrapError(
            TrustBootstrapError.Reason.ANCHOR_EXPIRED,
            f"anchor for {root!r} is present but inactive (expired or pending refresh); "
            f"retry is legitimate only within the refresh window",
        )

    depth_ok = [a for a in active if chain.delegation_depth <= a.max_delegation_depth]
    if not depth_ok:
        raise TrustBootstrapError(
            TrustBootstrapError.Reason.DEPTH_EXCEEDED,
            f"delegation depth {chain.delegation_depth} exceeds anchor limit "
            f"{active[0].max_delegation_depth} for {root!r}",
        )

    return depth_ok[0]
