# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocating-auditors-when-heterogeneous-fleets-vote-at-different-reasoning-depths.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocating-auditors-when-heterogeneous-fleets-vote-at-different-reasoning-depths.warrant.json
# Markdown SHA-256:   f14ff1fefc22c0bae036f8374715518e0bc1a1343f13ea50dcb513a4ba82cdc9
# Code AST SHA-256:   7627e3742876adc026e38b6161727db3c2336ff1975604bc3400afa0b7b06565
# Verified Classes:   DepthClass, EquivocationAmbiguous, SignedVote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class DepthClass(Enum):
    SHALLOW = "shallow"
    STANDARD = "standard"
    DEEP = "deep"


DEPTH_ORDER = {DepthClass.SHALLOW: 0, DepthClass.STANDARD: 1, DepthClass.DEEP: 2}


class EquivocationAmbiguous(RuntimeError):
    """Raised when a vote flip cannot be classified as re-derivation or equivocation."""


@dataclass
class SignedVote:
    auditor_id: str
    proposal_id: str
    verdict: str  # "ACCEPT" | "REJECT"
    trace_hash: str
    depth_class: DepthClass
    trace: str


def classify_vote_flip(prior: SignedVote, current: SignedVote) -> str:
    if prior.auditor_id != current.auditor_id or prior.proposal_id != current.proposal_id:
        raise EquivocationAmbiguous("vote flip comparison requires same auditor and proposal")

    if prior.verdict == current.verdict:
        return "no_flip"

    # Same trace, different verdict: only possible via equivocation.
    if prior.trace_hash == current.trace_hash:
        return "equivocation"

    # Diffuse divergence: cannot be explained by depth-class re-derivation.
    divergence = _normalized_edit_distance(prior.trace, current.trace)
    if divergence >= 0.15:
        return "equivocation"

    # Verdict flip must be monotonic in reasoning depth to count as re-derivation.
    prior_rank = DEPTH_ORDER[prior.depth_class]
    current_rank = DEPTH_ORDER[current.depth_class]
    if prior_rank == current_rank:
        raise EquivocationAmbiguous(
            f"same depth class {prior.depth_class} but verdict flipped with "
            f"divergence={divergence:.3f}; no depth explanation available"
        )

    deeper = prior if prior_rank > current_rank else current
    if deeper.verdict == "REJECT":
        return "re_derivation"
    # Deeper vote is ACCEPT while shallower is REJECT: non-monotonic, suspicious.
    return "equivocation"


def _normalized_edit_distance(a: str, b: str) -> float:
    if not a and not b:
        return 0.0
    # Levenshtein, normalized by longer length. Omitted for brevity; standard DP.
    longer = max(len(a), len(b))
    return _levenshtein(a, b) / longer


def _levenshtein(a: str, b: str) -> int:
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        cur = [i]
        for j, cb in enumerate(b, 1):
            cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
        prev = cur
    return prev[-1]


def tally_with_depth_quorum(
    votes: list[SignedVote],
    quorum: int,
    requires_deep: bool,
) -> Optional[str]:
    accepts = [v for v in votes if v.verdict == "ACCEPT"]
    if len(accepts) < quorum:
        return None
    if requires_deep and not any(v.depth_class == DepthClass.DEEP for v in accepts):
        raise EquivocationAmbiguous(
            "quorum reached without a deep-class vote on an edge-case-sensitive proposal"
        )
    return "ACCEPT"
