# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-equivocating-quorum-votes-when-federation-peers-sign-divergent-state-roots-under-byzantine-quorum-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-equivocating-quorum-votes-when-federation-peers-sign-divergent-state-roots-under-byzantine-quorum-consensus.warrant.json
# Markdown SHA-256:   cd5b751a27b686a8e2dded22646b9f98b2bc1fda6fa99b97b1032c7adccfbaae
# Code AST SHA-256:   44a9c8abed4d7f1188a1850852f577e2577660c3d5eda650defdb7e8e0b79050
# Verified Classes:   EquivocationOnResumeError, Signature, SignatureJournal
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Optional


class EquivocationOnResumeError(RuntimeError):
    """Raised when a resumed instance would sign a divergent root for an already-signed view."""


@dataclass(frozen=True)
class Signature:
    signer_id: str
    task_id: str
    view: int
    state_root: str
    sig: str


class SignatureJournal:
    """Durable, fsync'd record of every (signer, task_id, view) -> state_root ever signed."""

    def __init__(self, path: str):
        self.path = path
        self._entries: dict[tuple[str, str, int], str] = {}

    def load(self) -> None:
        try:
            with open(self.path) as f:
                for line in f:
                    e = json.loads(line)
                    self._entries[(e["signer_id"], e["task_id"], e["view"])] = e["state_root"]
        except FileNotFoundError:
            pass

    def record(self, signer_id: str, task_id: str, view: int, state_root: str) -> None:
        # Durability-before-gossip: write and fsync before returning.
        with open(self.path, "a") as f:
            f.write(json.dumps({
                "signer_id": signer_id, "task_id": task_id,
                "view": view, "state_root": state_root,
            }) + "\n")
            f.flush()
            import os
            os.fsync(f.fileno())
        self._entries[(signer_id, task_id, view)] = state_root

    def lookup(self, signer_id: str, task_id: str, view: int) -> Optional[str]:
        return self._entries.get((signer_id, task_id, view))


def sign_for_view(
    journal: SignatureJournal,
    signer_id: str,
    task_id: str,
    view: int,
    recomputed_root: str,
) -> Signature:
    prior = journal.lookup(signer_id, task_id, view)
    if prior is not None and prior != recomputed_root:
        # Honest signer diverged across resume. Do NOT re-sign; force view change.
        raise EquivocationOnResumeError(
            f"signer={signer_id} task={task_id} view={view} "
            f"prior_root={prior[:12]} recomputed_root={recomputed_root[:12]}: "
            f"refusing to sign divergent root; emit ViewChange(view+1)"
        )
    root = prior if prior is not None else recomputed_root
    journal.record(signer_id, task_id, view, root)
    sig = hashlib.sha256(f"{signer_id}:{task_id}:{view}:{root}".encode()).hexdigest()
    return Signature(signer_id, task_id, view, root, sig)
