# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-re-attest-its-own-delegation-chain-after-a-credential-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-re-attest-its-own-delegation-chain-after-a-credential-refresh.warrant.json
# Markdown SHA-256:   ba1e9ef452cc00e7d565332fa750167ad2333e9cea57235cf91a4418aa42d118
# Code AST SHA-256:   35a80c88d050dbeec35a4d300d9df1dd5b2834dc6ede1f694bd8eb31e78fa728
# Verified Classes:   DelegationAuthorityDrift, DelegationClaims, DownstreamEndorsement, RefreshHandler
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class DelegationAuthorityDrift(RuntimeError):
    """Raised when a refreshed credential's delegation claims no longer match
    the fingerprint under which downstream endorsements were signed."""
    pass


@dataclass(frozen=True)
class DelegationClaims:
    can_delegate: bool
    depth_remaining: int
    delegable_scopes: FrozenSet[str]
    issuer_policy_version: str

    def fingerprint(self) -> str:
        return (
            f"{int(self.can_delegate)}|{self.depth_remaining}|"
            f"{','.join(sorted(self.delegable_scopes))}|{self.issuer_policy_version}"
        )


@dataclass
class DownstreamEndorsement:
    sub_agent_id: str
    signed_under_fingerprint: str


class RefreshHandler:
    def __init__(self) -> None:
        self._endorsements: list[DownstreamEndorsement] = []

    def on_refresh(
        self,
        prior: DelegationClaims,
        refreshed: DelegationClaims,
        signature_valid: bool,
        subject_matches: bool,
    ) -> None:
        # Local validity checks — necessary but NOT sufficient.
        if not signature_valid or not subject_matches:
            raise DelegationAuthorityDrift(
                "refreshed credential failed local signature/subject validation"
            )

        prior_fp = prior.fingerprint()
        new_fp = refreshed.fingerprint()

        if prior_fp == new_fp:
            return  # authority unchanged; downstream endorsements remain valid

        # Authority changed. Determine direction.
        authority_lost = (
            (prior.can_delegate and not refreshed.can_delegate)
            or refreshed.depth_remaining < prior.depth_remaining
            or not prior.delegable_scopes.issubset(refreshed.delegable_scopes)
        )

        if authority_lost:
            stale = [
                e for e in self._endorsements
                if e.signed_under_fingerprint == prior_fp
            ]
            if stale:
                # Fail closed: refuse dispatch until sub-agents re-issue.
                self._endorsements = [
                    e for e in self._endorsements
                    if e.signed_under_fingerprint != prior_fp
                ]
                raise DelegationAuthorityDrift(
                    f"delegation authority downgraded on refresh "
                    f"({prior_fp} -> {new_fp}); revoked {len(stale)} downstream "
                    f"endorsement(s): {[e.sub_agent_id for e in stale]}"
                )
        else:
            # Authority widened: re-sign existing endorsements under new fingerprint.
            self._endorsements = [
                DownstreamEndorsement(e.sub_agent_id, new_fp)
                for e in self._endorsements
            ]

    def endorse(self, sub_agent_id: str, current: DelegationClaims) -> None:
        if not current.can_delegate or current.depth_remaining < 1:
            raise DelegationAuthorityDrift(
                f"cannot endorse {sub_agent_id}: can_delegate="
                f"{current.can_delegate}, depth={current.depth_remaining}"
            )
        self._endorsements.append(
            DownstreamEndorsement(sub_agent_id, current.fingerprint())
        )
