# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-omission-in-bft-task-commitment-quorums-when-a-peer-s-signed-commitment-set-is-internally-consistent-but-m.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-omission-in-bft-task-commitment-quorums-when-a-peer-s-signed-commitment-set-is-internally-consistent-but-m.warrant.json
# Markdown SHA-256:   ffd382ef82425c07438539f459e79a00fa0a1289985e8aaca66ecf63fbad45d9
# Code AST SHA-256:   bb40ffd87f0df795b2e934f945ed59a4822230937af16aa10ddad46d5b07fb52
# Verified Classes:   EquivocationByOmissionError, ProjectionFunctionMismatchError, Commitment, SignedCommitmentCertificate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Iterable


class EquivocationByOmissionError(RuntimeError):
    """Raised when a peer's signed commitment set is internally valid but
    mutually unsatisfiable against its signed resource envelope."""
    pass


class ProjectionFunctionMismatchError(RuntimeError):
    """Raised when an SCP's pinned projection-function hash does not match
    the adjudicator's spec — the projection cannot be used as proof."""
    pass


@dataclass(frozen=True)
class Commitment:
    task_id: str
    deadline_epoch: int
    resource_class: str
    estimated_units: float


@dataclass(frozen=True)
class SignedCommitmentCertificate:
    peer_id: str
    epoch: int
    envelope_units: float          # signed in registration cert, not per-SCP
    horizon_epoch: int
    commitments: tuple[Commitment, ...]
    projection_spec_hash: str      # hash of the feasibility model used
    signature: bytes               # assumed verified upstream


PROJECTION_SPEC_HASH = hashlib.sha256(
    b"projection:v3:sum_units_by_deadline_within_class"
).hexdigest()

ESTIMATE_SLACK = 0.05  # epsilon, recomputed from history in production


def project_overcommitment(
    certs: Iterable[SignedCommitmentCertificate],
) -> tuple[int, float]:
    """Return (worst_epoch, rho) where rho is the max projected
    over-commitment ratio across the horizon. Pure function; this is the
    hash-pinned feasibility model."""
    certs = tuple(certs)
    if not certs:
        return (0, 0.0)

    for c in certs:
        if c.projection_spec_hash != PROJECTION_SPEC_HASH:
            raise ProjectionFunctionMismatchError(
                f"peer {c.peer_id} epoch {c.epoch} pinned projection "
                f"{c.projection_spec_hash[:12]} != spec "
                f"{PROJECTION_SPEC_HASH[:12]}; projection inadmissible as proof"
            )

    envelope = certs[0].envelope_units
    horizon = certs[0].horizon_epoch

    # Sum units per (resource_class, deadline) across ALL epochs.
    load: dict[tuple[str, int], float] = {}
    for c in certs:
        for cm in c.commitments:
            key = (cm.resource_class, cm.deadline_epoch)
            load[key] = load.get(key, 0.0) + cm.estimated_units

    worst_epoch, worst_rho = 0, 0.0
    for target in range(1, horizon + 1):
        # Units with deadline <= target must fit within envelope by target.
        total = sum(u for (cls, dl), u in load.items() if dl <= target)
        rho = total / envelope if envelope > 0 else float("inf")
        if rho > worst_rho:
            worst_epoch, worst_rho = target, rho

    return (worst_epoch, worst_rho)


def validate_and_sign(
    certs: Iterable[SignedCommitmentCertificate],
) -> str:
    """Called BEFORE the instance co-signs the latest SCP. Returns a
    decision string; raises on slashable over-commitment."""
    certs = tuple(certs)
    if not certs:
        raise EquivocationByOmissionError("empty certificate set")

    worst_epoch, rho = project_overcommitment(certs)

    if rho > 1.0 + ESTIMATE_SLACK:
        latest = certs[-1]
        raise EquivocationByOmissionError(
            f"peer {latest.peer_id} epoch {latest.epoch}: projected "
            f"over-commitment rho={rho:.3f} at epoch {worst_epoch} "
            f"exceeds envelope by {(rho - 1.0) * 100:.1f}% "
            f"(slack {ESTIMATE_SLACK:.0%}); SCP is internally valid but "
            f"mutually unsatisfiable — refuse to co-sign, raise challenge"
        )

    if rho > 1.0:
        return f"accept-with-reservation:rho={rho:.3f},epoch={worst_epoch}"
    return f"accept:rho={rho:.3f}"
