# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-plan-whose-quorum-certificate-is-valid-but-whose-view-change-proof-is-stale.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-plan-whose-quorum-certificate-is-valid-but-whose-view-change-proof-is-stale.warrant.json
# Markdown SHA-256:   9b009ea054fc0eb9d7492eae0fd1611a435e4e4e11e3b07931fbbc555de68540
# Code AST SHA-256:   4c41da4eea6c42f57e50cbbf4eb96449211447bd113a4f48a74e2c829f001b11
# Verified Classes:   StaleViewChangeProofError, QC, VCPDisclosure, ViewChangeProof
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable, Mapping


class StaleViewChangeProofError(RuntimeError):
    """Raised when a VCP is signature-valid but its highQC is not the true maximum."""


@dataclass(frozen=True)
class QC:
    block_hash: str
    height: int


@dataclass(frozen=True)
class VCPDisclosure:
    validator_id: int
    highest_qc: QC
    signature: bytes


@dataclass(frozen=True)
class ViewChangeProof:
    view: int
    high_qc: QC
    disclosures: tuple[VCPDisclosure, ...]
    quorum_size: int


def verify_vcp_freshness(
    vcp: ViewChangeProof,
    known_qcs_by_validator: Mapping[int, QC],
) -> None:
    """
    Enforce that the VCP's highQC dominates every disclosure in its quorum
    and that no signer's true highest QC (per independent observation) exceeds it.
    Raises StaleViewChangeProofError if the VCP understates the maximum.
    """
    if len(vcp.disclosures) < vcp.quorum_size:
        raise StaleViewChangeProofError(
            f"VCP for view {vcp.view} has {len(vcp.disclosures)} disclosures, "
            f"needs {vcp.quorum_size}"
        )

    disclosed_max = max((d.highest_qc for d in vcp.disclosures), key=lambda q: q.height)
    if disclosed_max.height > vcp.high_qc.height:
        raise StaleViewChangeProofError(
            f"VCP for view {vcp.view} claims highQC height {vcp.high_qc.height} "
            f"but a disclosure reports height {disclosed_max.height}"
        )

    for d in vcp.disclosures:
        observed = known_qcs_by_validator.get(d.validator_id)
        if observed is None:
            continue
        if observed.height > vcp.high_qc.height:
            raise StaleViewChangeProofError(
                f"VCP for view {vcp.view} is stale: validator {d.validator_id} "
                f"independently observed QC height {observed.height} > "
                f"claimed highQC height {vcp.high_qc.height}"
            )


def commit_plan(
    plan_hash: str,
    qc: QC,
    vcp: ViewChangeProof,
    known_qcs_by_validator: Mapping[int, QC],
) -> str:
    """
    Commit a plan only if the QC is valid AND the VCP that produced its view
    is fresh. Returns the committed plan hash.
    """
    if qc.block_hash != plan_hash:
        raise StaleViewChangeProofError(
            f"QC covers block {qc.block_hash}, not requested plan {plan_hash}"
        )
    verify_vcp_freshness(vcp, known_qcs_by_validator)
    return plan_hash
