# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-tamper-evident-audit-chain-when-a-peer-organization-s-signing-key-rotates-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-tamper-evident-audit-chain-when-a-peer-organization-s-signing-key-rotates-mid-handoff.warrant.json
# Markdown SHA-256:   ae7606871451572ebe0cfd0611438aa71b6a67ea589afb98a279e8d04da14da4
# Code AST SHA-256:   b9a27c301e7206ade3e9ea823c83e411087987ecd25ad89aff245913982f21ba
# Verified Classes:   AuditChainViolation, TransitionRecord, Segment
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class AuditChainViolation(RuntimeError):
    """Raised when a federated audit chain cannot be validated under its own key-transition records."""


@dataclass(frozen=True)
class TransitionRecord:
    retiring_key_fp: str
    new_key_fp: str
    effective_at: int          # unix seconds
    countersignature: bytes    # signature by retiring key over new_key_fp + effective_at
    prev_segment_hash: str


@dataclass(frozen=True)
class Segment:
    signed_at: int
    signer_key_fp: str
    payload_hash: str
    prev_hash: str
    signature: bytes


def resolve_authoritative_key(
    seg: Segment,
    transitions: list[TransitionRecord],
    verify_sig,
) -> str:
    """
    Return the key fingerprint that was authoritative for seg.signed_at,
    or raise AuditChainViolation if no in-chain transition covers it.

    The chain, not a live JWKS endpoint, is the authority.
    """
    candidates = [
        t for t in transitions
        if t.effective_at <= seg.signed_at
        and (t.new_key_fp == seg.signer_key_fp or t.retiring_key_fp == seg.signer_key_fp)
    ]
    if not candidates:
        raise AuditChainViolation(
            f"no transition record covers signed_at={seg.signed_at} "
            f"for signer={seg.signer_key_fp}; segment must be quarantined, not accepted"
        )

    # The transition must be countersigned by the retiring key, otherwise it is
    # a self-assertion and provides no continuity across the seam.
    latest = max(candidates, key=lambda t: t.effective_at)
    if not verify_sig(
        key_fp=latest.retiring_key_fp,
        message=latest.new_key_fp.encode() + str(latest.effective_at).encode(),
        signature=latest.countersignature,
    ):
        raise AuditChainViolation(
            f"transition {latest.retiring_key_fp}->{latest.new_key_fp} lacks a valid "
            f"retiring-key countersignature; rotation is a trust reset, not a rotation"
        )

    if latest.new_key_fp != seg.signer_key_fp and latest.retiring_key_fp != seg.signer_key_fp:
        raise AuditChainViolation(
            f"segment signer {seg.signer_key_fp} is not bound by any transition "
            f"effective at {seg.signed_at}"
        )
    return seg.signer_key_fp


def replay_chain(
    segments: list[Segment],
    transitions: list[TransitionRecord],
    verify_sig,
) -> list[str]:
    """
    Replay a federated audit chain. Returns the list of quarantined segment
    indices; raises AuditChainViolation on genuine integrity failure.
    """
    quarantined: list[str] = []
    prev_hash = segments[0].prev_hash if segments else ""

    for i, seg in enumerate(segments):
        if seg.prev_hash != prev_hash:
            raise AuditChainViolation(
                f"segment {i}: hash link broken "
                f"(expected {prev_hash[:12]}, got {seg.prev_hash[:12]})"
            )

        try:
            key_fp = resolve_authoritative_key(seg, transitions, verify_sig)
        except AuditChainViolation:
            # Missing/uncountersigned transition is an availability problem,
            # not an integrity proof. Quarantine, do not abort.
            quarantined.append(f"segment_{i}:provenance_unresolved")
            prev_hash = hashlib.sha256(
                seg.payload_hash.encode() + seg.prev_hash.encode()
            ).hexdigest()
            continue

        if not verify_sig(key_fp=key_fp, message=seg.payload_hash.encode(), signature=seg.signature):
            raise AuditChainViolation(
                f"segment {i}: signature invalid against authoritative key {key_fp}"
            )

        prev_hash = hashlib.sha256(
            seg.payload_hash.encode() + seg.prev_hash.encode()
        ).hexdigest()

    return quarantined
