# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-valid-but-superseded-revocation-log-entry-as-a-hard-trust-failure-during-cross-org-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-valid-but-superseded-revocation-log-entry-as-a-hard-trust-failure-during-cross-org-agent-federation.warrant.json
# Markdown SHA-256:   03e13808d92af25d79d684d0752cee7ea4cc46134191969879a51bc76113bec3
# Code AST SHA-256:   fdecd697e207ae05fb2fc9cce529eac12869696db5569c4f955afa6d9788559e
# Verified Classes:   StaleTreeHeadError, LogEquivocationError, RevocationLaunderingError, TreeHead, Manifest, FederatedTrustVerifier
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class StaleTreeHeadError(RuntimeError):
    """Raised when a manifest's inclusion proof is anchored to a tree head
    that does not dominate the verifier's observed high-water mark."""
    pass


class LogEquivocationError(RuntimeError):
    """Raised when the log's consistency proof between the verifier's
    high-water mark and the presented tree head fails to verify."""
    pass


class RevocationLaunderingError(RuntimeError):
    """Raised when a manifest's supersession ancestor is revoked in the
    presented tree head's prefix, even though the manifest itself is not."""
    pass


@dataclass(frozen=True)
class TreeHead:
    tree_size: int
    root_hash: bytes
    log_id: str


@dataclass(frozen=True)
class Manifest:
    agent_id: str
    manifest_hash: bytes
    supersedes: Optional[bytes]
    sth: TreeHead
    inclusion_proof: bytes
    signature: bytes


class FederatedTrustVerifier:
    def __init__(self, log_id: str, persisted_high_water: Optional[TreeHead] = None):
        self.log_id = log_id
        # High-water mark MUST be loaded from durable storage, not defaulted to None
        # unless this is genuinely first contact with a cosigned anchor.
        self.high_water_mark: Optional[TreeHead] = persisted_high_water

    def _verify_consistency(self, old: TreeHead, new: TreeHead) -> bool:
        # Placeholder for RFC 6962 consistency proof verification.
        return new.tree_size >= old.tree_size and new.root_hash != b""

    def _verify_inclusion(self, manifest: Manifest) -> bool:
        return len(manifest.inclusion_proof) > 0

    def _revoked_in_prefix(self, manifest_hash: bytes, sth: TreeHead) -> bool:
        return False  # query log's revocation set at sth.tree_size

    def verify(self, manifest: Manifest) -> bool:
        if manifest.sth.log_id != self.log_id:
            raise StaleTreeHeadError(
                f"manifest anchored to foreign log {manifest.sth.log_id}"
            )

        if self.high_water_mark is not None:
            if manifest.sth.tree_size < self.high_water_mark.tree_size:
                raise StaleTreeHeadError(
                    f"presented STH size {manifest.sth.tree_size} < "
                    f"high-water mark {self.high_water_mark.tree_size}; "
                    f"refusing stale-prefix proof"
                )
            if not self._verify_consistency(self.high_water_mark, manifest.sth):
                raise LogEquivocationError(
                    f"consistency proof failed between "
                    f"{self.high_water_mark.tree_size} and {manifest.sth.tree_size}"
                )

        if not self._verify_inclusion(manifest):
            raise StaleTreeHeadError("inclusion proof invalid")

        if self._revoked_in_prefix(manifest.manifest_hash, manifest.sth):
            raise RevocationLaunderingError(
                f"manifest {manifest.agent_id} is revoked in prefix "
                f"{manifest.sth.tree_size}"
            )

        # Walk supersession chain: a successor must not inherit revoked authority.
        ancestor = manifest.supersedes
        seen = set()
        while ancestor is not None and ancestor not in seen:
            seen.add(ancestor)
            if self._revoked_in_prefix(ancestor, manifest.sth):
                raise RevocationLaunderingError(
                    f"manifest {manifest.agent_id} supersedes revoked ancestor "
                    f"{ancestor.hex()}"
                )
            ancestor = None  # resolve next ancestor via log lookup

        # Ratchet forward BEFORE returning: closes the exposure window.
        self.high_water_mark = manifest.sth
        return True
