# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-sign-its-own-delegation-chain-the-key-rotation-witness-gap-in-aaif-verifiable-credential-issuance.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-sign-its-own-delegation-chain-the-key-rotation-witness-gap-in-aaif-verifiable-credential-issuance.warrant.json
# Markdown SHA-256:   fbedb560bedb0bb7e5fb2c266fed7e3542fd5af37a3f4a5bbf933e589ac3fdcb
# Code AST SHA-256:   12ba098c117e07b3bd5955537b95f4171f580a3ecdd080e1dc5651a153c6bfad
# Verified Classes:   WitnessGapError, KeyHistoryEntry, CredentialDraft
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class WitnessGapError(RuntimeError):
    """Raised when an issuer cannot bridge policy_epoch to signing_epoch
    with a complete, control-plane-signed key-history witness."""


@dataclass(frozen=True)
class KeyHistoryEntry:
    from_key: str
    to_key: str
    from_epoch: int
    to_epoch: int
    control_plane_sig: str


@dataclass(frozen=True)
class CredentialDraft:
    subject: str
    capability_scope: str
    policy_epoch: int
    signing_epoch: int
    signing_key_id: str


def resolve_witness_chain(
    history: list[KeyHistoryEntry],
    policy_epoch: int,
    signing_epoch: int,
) -> list[KeyHistoryEntry]:
    """Return the ordered witness chain bridging policy_epoch -> signing_epoch.
    Raises WitnessGapError on any gap, inversion, or unsigned entry."""
    if policy_epoch == signing_epoch:
        return []
    chain: list[KeyHistoryEntry] = []
    cursor = policy_epoch
    while cursor < signing_epoch:
        step = next(
            (h for h in history if h.from_epoch == cursor and h.to_epoch == cursor + 1),
            None,
        )
        if step is None:
            raise WitnessGapError(
                f"no witness entry bridging epoch {cursor} -> {cursor + 1}; "
                f"credential would be semantically orphaned"
            )
        if not step.control_plane_sig:
            raise WitnessGapError(
                f"witness entry {step.from_epoch}->{step.to_epoch} is unsigned; "
                f"cannot attest rotation provenance"
            )
        chain.append(step)
        cursor = step.to_epoch
    return chain


def issue_credential(
    draft: CredentialDraft,
    history: list[KeyHistoryEntry],
) -> dict:
    """Gate issuance on witness resolvability. Refuse rather than orphan."""
    try:
        witness = resolve_witness_chain(
            history, draft.policy_epoch, draft.signing_epoch
        )
    except WitnessGapError as exc:
        # Correct behavior: block issuance. Do NOT fall back to old-key signing
        # (replay risk) or new-key signing without witness (orphaning risk).
        raise WitnessGapError(
            f"refusing to sign credential for {draft.subject!r}: {exc}"
        ) from exc

    return {
        "subject": draft.subject,
        "capability_scope": draft.capability_scope,
        "policy_epoch": draft.policy_epoch,
        "signing_epoch": draft.signing_epoch,
        "signing_key_id": draft.signing_key_id,
        "predecessor_witness": [
            {
                "from_epoch": w.from_epoch,
                "to_epoch": w.to_epoch,
                "control_plane_sig": w.control_plane_sig,
            }
            for w in witness
        ],
    }
