# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-peer-s-silence-as-evidence-of-deadlock-rather-than-as-evidence-of-liveness.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-peer-s-silence-as-evidence-of-deadlock-rather-than-as-evidence-of-liveness.warrant.json
# Markdown SHA-256:   eaf129c499c054ccfb4a4b38a5cb3d66833f2b970eaa4f687f5816d6c48221d5
# Code AST SHA-256:   9a9f840f8c1bf4e800257e124ba7fae32ab84f0f3e0b37ef85a0c7a45fe83455
# Verified Classes:   DeadlockUndecidable, DetectionState, EdgeReport, Detector
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Hashable

PeerId = Hashable


class DeadlockUndecidable(RuntimeError):
    """Raised when a detector cannot prove or disprove a cycle under partial observability.

    This is NOT a deadlock and NOT a clear. Releasing held resources in this state
    is the exact action that lets a Byzantine silencer mask a real ring.
    """


class DetectionState(Enum):
    NO_DEADLOCK = "no_deadlock"
    DEADLOCKED = "deadlocked"
    UNDECIDABLE = "undecidable"


@dataclass
class EdgeReport:
    src: PeerId
    dst: PeerId
    epoch: int
    reporter: PeerId  # who attested this edge


@dataclass
class Detector:
    self_id: PeerId
    epoch: int
    reports: list[EdgeReport] = field(default_factory=list)
    suspected: set[PeerId] = field(default_factory=set)
    quorum_size: int = 3  # 2f+1 with f=1

    def _honest_edges(self) -> dict[PeerId, set[PeerId]]:
        # Rule 3: drop mixed-epoch edges. Rule 4: drop edges touching suspects.
        graph: dict[PeerId, set[PeerId]] = {}
        for r in self.reports:
            if r.epoch != self.epoch:
                continue
            if r.src in self.suspected or r.dst in self.suspected:
                continue
            graph.setdefault(r.src, set()).add(r.dst)
        return graph

    def _find_cycle(self, graph: dict[PeerId, set[PeerId]]) -> list[PeerId] | None:
        WHITE, GRAY, BLACK = 0, 1, 2
        color: dict[PeerId, int] = {}
        stack: list[PeerId] = []

        def dfs(node: PeerId) -> list[PeerId] | None:
            color[node] = GRAY
            stack.append(node)
            for nxt in graph.get(node, ()):
                c = color.get(nxt, WHITE)
                if c == GRAY:
                    return stack[stack.index(nxt):] + [nxt]
                if c == WHITE:
                    found = dfs(nxt)
                    if found:
                        return found
            stack.pop()
            color[node] = BLACK
            return None

        for node in list(graph):
            if color.get(node, WHITE) == WHITE:
                found = dfs(node)
                if found:
                    return found
        return None

    def _cycle_is_attested(self, cycle: list[PeerId]) -> bool:
        # Rule 1: every cycle edge attested by its source or by a reporter != source.
        # Rule 2: certifying reporters must exclude the accused peers in the cycle.
        cycle_set = set(cycle)
        for a, b in zip(cycle, cycle[1:]):
            attestors = {
                r.reporter
                for r in self.reports
                if r.epoch == self.epoch and r.src == a and r.dst == b
            }
            if not attestors:
                return False
            if not (attestors - cycle_set):
                # only the accused vouch for the edge closing a cycle through them
                return False
        return True

    def evaluate(self) -> DetectionState:
        graph = self._honest_edges()

        # Case: honest subgraph already contains a cycle -> provable deadlock.
        cycle = self._find_cycle(graph)
        if cycle is not None:
            if not self._cycle_is_attested(cycle):
                raise DeadlockUndecidable(
                    f"cycle {cycle} found but closure attested only by accused peers; "
                    "escalate to coordinator, do not abort"
                )
            return DetectionState.DEADLOCKED

        # Case: no cycle among honest peers, but suspects exist -> undecidable.
        if self.suspected:
            live = set(graph) | {d for ds in graph.values() for d in ds}
            relevant = any(
                s in live or any(s in ds for ds in graph.values())
                for s in self.suspected
            )
            if relevant:
                raise DeadlockUndecidable(
                    f"honest subgraph acyclic but suspects {sorted(map(str, self.suspected))} "
                    "sit on the wait structure; a hidden cycle cannot be ruled out. "
                    "Hold resources, escalate to quorum audit."
                )

        return DetectionState.NO_DEADLOCK


def run_detection(detector: Detector) -> DetectionState:
    state = detector.evaluate()
    if state is DetectionState.UNDECIDABLE:
        # Defensive: evaluate() raises, but a future refactor must not silently pass.
        raise DeadlockUndecidable("detector returned UNDECIDABLE without escalation path")
    return state
