# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-aaif-trust-root-when-the-revocation-list-itself-is-served-under-the-revoked-root.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-aaif-trust-root-when-the-revocation-list-itself-is-served-under-the-revoked-root.warrant.json
# Markdown SHA-256:   1271bb8036059c212769148b18b0a79d2d81b5b74e5110d1468eaa924e49d3b5
# Code AST SHA-256:   f0472f277fd17da2f9b58fe4ac71eb91ffc8b85189ef7f65d1ceb225ae7370ad
# Verified Classes:   TrustUnverifiable, Anchor, Manifest, TrustStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TrustUnverifiable(RuntimeError):
    """Raised when revocation state cannot be established from an independent anchor."""
    pass


@dataclass
class Anchor:
    root_id: str
    not_after: float
    # provenance is 'enrollment' (out-of-band pin) or 'derived' (learned from a bundle)
    provenance: str


@dataclass
class Manifest:
    signed_by: str
    revoked: list[str]
    countersigned_by: Optional[str] = None


@dataclass
class TrustStore:
    anchors: dict[str, Anchor] = field(default_factory=dict)

    def independent_successor(self, retiring_root: str) -> Optional[Anchor]:
        for a in self.anchors.values():
            if a.root_id != retiring_root and a.provenance == "enrollment":
                if a.not_after > time.time():
                    return a
        return None


def evaluate_refresh(store: TrustStore, manifest: Manifest, now: float) -> str:
    # Step 1: any live pinned anchor at all?
    live = [a for a in store.anchors.values() if a.not_after > now]
    if not live:
        raise TrustUnverifiable(
            f"no live anchor; cannot establish revocation state for {manifest.signed_by}"
        )

    # Step 2: is the only validating signer self-revoked?
    signer = store.anchors.get(manifest.signed_by)
    if signer is None:
        raise TrustUnverifiable(
            f"manifest signed by unknown root {manifest.signed_by}"
        )
    self_revoked = manifest.signed_by in manifest.revoked

    if not self_revoked:
        # Normal path: signer is trusted and not revoking itself.
        for r in manifest.revoked:
            store.anchors.pop(r, None)
        return "clean"

    # Step 3: self-revocation. A countersignature carried inside the
    # self-revoked payload is circular and does not count.
    successor = store.independent_successor(manifest.signed_by)
    if successor is None:
        # Null result, NOT a negative result. Degrade, do not accept.
        raise TrustUnverifiable(
            f"root {manifest.signed_by} self-revoked with no independent successor; "
            f"revocation state is unverifiable, not clean"
        )

    # Successor is independently pinned: promote and re-evaluate.
    store.anchors.pop(manifest.signed_by, None)
    for r in manifest.revoked:
        store.anchors.pop(r, None)
    return f"degraded->promoted:{successor.root_id}"
