# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-delegation-warrant-when-a-credential-is-re-issued-mid-chain-rather-than-re-signed-end-to-end.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-delegation-warrant-when-a-credential-is-re-issued-mid-chain-rather-than-re-signed-end-to-end.warrant.json
# Markdown SHA-256:   01968053e882b48af247a03ca4efa35b85f65cb74a0fc4a8ac55ff4324fdf8b5
# Code AST SHA-256:   e23ea2effd4d3fe710798846c4e005ba11d154dfdc9b8fb652791d642ef91fbc
# Verified Classes:   LineageDiscontinuityError, Credential
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from datetime import datetime, timedelta


class LineageDiscontinuityError(RuntimeError):
    """Raised when a delegated warrant's referenced ancestor is superseded
    but still resolvable, or when an ancestor's issuer key has aged out
    before the leaf's own expiry. Distinct from revocation."""
    pass


@dataclass
class Credential:
    credential_id: str
    issuer_did: str
    subject_did: str
    parent_hash: str | None          # hash of the credential this descends from
    not_after: datetime
    key_retention_until: datetime    # when this issuer's signing key stops being published
    content_hash: str                # hash of the signed body; changes on any re-issue


def resolve_lineage(leaf: Credential, registry: dict[str, Credential],
                    active_by_subject: dict[str, str]) -> str:
    """Walk the chain from leaf to root. Returns one of
    'VALID' | 'ORPHANED' | 'UNVERIFIABLE'.

    ORPHANED: every link verifies against retained keys, but some link
    references an ancestor that is no longer the issuer's active issuance.
    This is NOT revocation and must trigger re-issuance, not denial.
    """
    node = leaf
    seen = set()
    orphaned = False

    while node.parent_hash is not None:
        if node.parent_hash in seen:
            raise LineageDiscontinuityError(
                f"cycle detected at {node.parent_hash}")
        seen.add(node.parent_hash)

        parent = registry.get(node.parent_hash)
        if parent is None:
            return "UNVERIFIABLE"

        # Grace window: if the referenced ancestor's issuer key is gone
        # before the leaf expires, the leaf cannot be verified for its
        # full lifetime.
        if parent.key_retention_until < leaf.not_after:
            raise LineageDiscontinuityError(
                f"ancestor {parent.credential_id} key retention "
                f"({parent.key_retention_until.isoformat()}) ends before "
                f"leaf {leaf.credential_id} expiry "
                f"({leaf.not_after.isoformat()}); leaf will be orphaned "
                f"into UNVERIFIABLE at grace expiry — re-issue required")

        # Is this parent still the issuer's designated-active credential
        # for its subject? If not, the child is referencing a superseded
        # node.
        active_id = active_by_subject.get(parent.subject_did)
        if active_id is not None and active_id != parent.credential_id:
            orphaned = True

        node = parent

    return "ORPHANED" if orphaned else "VALID"


def enforce_warrant(leaf: Credential, registry: dict[str, Credential],
                    active_by_subject: dict[str, str]) -> None:
    status = resolve_lineage(leaf, registry, active_by_subject)
    if status == "UNVERIFIABLE":
        raise LineageDiscontinuityError(
            f"warrant {leaf.credential_id}: referenced ancestor not "
            f"resolvable; failing closed")
    if status == "ORPHANED":
        raise LineageDiscontinuityError(
            f"warrant {leaf.credential_id}: chain references a superseded "
            f"ancestor; re-issue against current head before proceeding — "
            f"do NOT treat as revoked")
    # VALID: proceed
