# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-aaif-attestation-chain-silently-fork-when-a-credential-is-re-issued-across-an-attestation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-aaif-attestation-chain-silently-fork-when-a-credential-is-re-issued-across-an-attestation-boundary.warrant.json
# Markdown SHA-256:   2ec81ff94e6cc437777ca055fd6d91705cf7a8eff67965a374a9278e1c6617f1
# Code AST SHA-256:   5673f951b1d81a98f61552a29929efa3b5a90842ea52cbfa475a4574232eaacd
# Verified Classes:   AttestationForkError, Credential
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AttestationForkError(RuntimeError):
    """Raised when an AAIF chain resolves to zero or multiple leaves.

    A forked chain is an integrity violation, not a policy disagreement.
    Verifiers MUST refuse to render a verdict rather than pick a leaf.
    """


@dataclass
class Credential:
    cred_id: str
    issuer: str
    agent_id: str
    scope: frozenset
    not_before: float
    not_after: float
    supersedes: Optional[str] = None  # cred_id of prior credential, or None


def issue_reissuance(
    prior: Credential,
    new_cred_id: str,
    scope: frozenset,
    not_before: float,
    not_after: float,
    prior_revoked: bool,
) -> Credential:
    """Write-side guardrail: re-issuance MUST link to the prior credential.

    A re-issuance that flattens the chain (supersedes=None) while the prior
    credential remains valid creates a DAG fork. Fail closed here, at the
    issuer, not later at the verifier.
    """
    if not prior_revoked and prior.not_after > not_before:
        # prior credential still live in its grace window: supersession is mandatory
        return Credential(
            cred_id=new_cred_id,
            issuer=prior.issuer,
            agent_id=prior.agent_id,
            scope=scope,
            not_before=not_before,
            not_after=not_after,
            supersedes=prior.cred_id,  # explicit edge — no fork
        )
    # prior is revoked or expired: a fresh root is legitimate
    return Credential(
        cred_id=new_cred_id,
        issuer=prior.issuer,
        agent_id=prior.agent_id,
        scope=scope,
        not_before=not_before,
        not_after=not_after,
        supersedes=None,
    )


def resolve_unique_leaf(chain: list, now: float) -> Credential:
    """Read-side guardrail: resolve to a unique terminus of the supersedes DAG.

    Leaf selection MUST be a pure function of the supersedes graph, never of
    timestamp, window length, or scope cardinality. Zero or multiple leaves
    is an integrity fault — refuse to verdict.
    """
    by_id = {c.cred_id: c for c in chain}
    superseded = {c.supersedes for c in chain if c.supersedes is not None}
    leaves = [
        c for c in chain
        if c.cred_id not in superseded and c.not_before <= now <= c.not_after
    ]

    if len(leaves) == 0:
        raise AttestationForkError(
            f"no valid leaf for agent {chain[0].agent_id if chain else '?'}: "
            f"chain has no un-superseded credential in validity window"
        )
    if len(leaves) > 1:
        leaf_ids = sorted(l.cred_id for l in leaves)
        raise AttestationForkError(
            f"forked attestation chain for agent {leaves[0].agent_id}: "
            f"multiple valid leaves {leaf_ids} share a common ancestor; "
            f"refusing to render a trust verdict"
        )
    return leaves[0]
