# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-attest-a-delegated-capability-when-the-credential-s-subject-binding-is-preserved-but-its-issuer-chain-is-re-rooted-mid-deleg.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-attest-a-delegated-capability-when-the-credential-s-subject-binding-is-preserved-but-its-issuer-chain-is-re-rooted-mid-deleg.warrant.json
# Markdown SHA-256:   52f6f248b1e867997a9c96feaabb9ef1f70c54721d29a8bcf7534cae2b63c2b4
# Code AST SHA-256:   236c19d617215af91047bb0fbbfcba6df9e7ce73db153f9ea1b37a55094887a8
# Verified Classes:   ChainContinuityError, IssuerAuthorityLapsed, Credential, TrustConfig
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ChainContinuityError(RuntimeError):
    """Raised when a delegated credential's issuer chain cannot be walked to a trust anchor."""


class IssuerAuthorityLapsed(RuntimeError):
    """Raised when an intermediate issuer's authority VC is not valid at validation time."""


@dataclass
class Credential:
    subject_id: str
    issuer: str
    capability: str
    issuance_date: float
    parent_credential_hash: Optional[str] = None
    delegation_depth: int = 0
    proof_chain: list = field(default_factory=list)


@dataclass
class TrustConfig:
    root_anchors: set
    delegation_scoped_issuers: set
    reissuance_window_seconds: float = 300.0


def _hash(cred: Credential) -> str:
    return hashlib.sha256(
        f"{cred.subject_id}|{cred.issuer}|{cred.capability}|{cred.issuance_date}".encode()
    ).hexdigest()


def _resolve_parent(parent_hash: str, store: dict) -> Credential:
    if parent_hash not in store:
        raise ChainContinuityError(
            f"parentCredentialHash {parent_hash!r} unresolvable; chain is severed"
        )
    return store[parent_hash]


def _issuer_authority_valid(issuer: str, capability: str, at_time: float, store: dict) -> bool:
    for cred in store.values():
        if (
            cred.subject_id == issuer
            and cred.capability == f"issue:{capability}"
            and cred.issuance_date <= at_time
        ):
            return True
    return False


def validate_delegated_capability(
    presented: Credential,
    expected_subject: str,
    trust: TrustConfig,
    store: dict,
    now: float,
) -> None:
    if presented.subject_id != expected_subject:
        raise ChainContinuityError(
            f"subject binding mismatch: {presented.subject_id!r} != {expected_subject!r}"
        )

    reattest_required = False
    if presented.issuer in trust.delegation_scoped_issuers:
        reattest_required = True
    if presented.parent_credential_hash is not None:
        parent = _resolve_parent(presented.parent_credential_hash, store)
        if parent.issuer != presented.issuer:
            reattest_required = True
        if presented.issuance_date - parent.issuance_date > trust.reissuance_window_seconds:
            reattest_required = True
    if len(presented.proof_chain) < presented.delegation_depth:
        reattest_required = True

    if not reattest_required:
        return

    # Re-attest: walk the chain to a root anchor, validating each issuer's authority.
    cursor: Optional[Credential] = presented
    seen = set()
    while cursor is not None:
        if cursor.issuer in trust.root_anchors:
            return
        if cursor.issuer in seen:
            raise ChainContinuityError(f"issuer chain cycle at {cursor.issuer!r}")
        seen.add(cursor.issuer)

        if not _issuer_authority_valid(cursor.issuer, cursor.capability, now, store):
            raise IssuerAuthorityLapsed(
                f"issuer {cursor.issuer!r} has no valid authority for "
                f"{cursor.capability!r} at t={now}"
            )
        if cursor.parent_credential_hash is None:
            raise ChainContinuityError(
                f"chain from issuer {cursor.issuer!r} does not terminate at a root anchor"
            )
        cursor = _resolve_parent(cursor.parent_credential_hash, store)
