# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-mis-attribute-a-slashed-stake-when-reputation-weights-cross-an-organizational-boundary-mid-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-mis-attribute-a-slashed-stake-when-reputation-weights-cross-an-organizational-boundary-mid-epoch.warrant.json
# Markdown SHA-256:   5cf183ad2b882b9096fc207b31cdcd31f3171b2fe41cce016069b41ee6f7ab15
# Code AST SHA-256:   9a088f94a11694f9a59e53b276b962c3e38259ae04f94365bba9657bb582ea3d
# Verified Classes:   SlashAttributionError, Projection, Ledger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SlashAttributionError(RuntimeError):
    """Raised when a slashing event cannot be attributed to the bond-holding ledger."""


@dataclass(frozen=True)
class Projection:
    agent: str
    reputation: float
    weight: float
    epoch: int
    source_domain: str
    bond_domain: str
    sig_valid: bool


@dataclass
class Ledger:
    domain: str
    epoch: int
    stake: dict
    soft_slash_offset: dict


def apply_slash(
    agent: str,
    ledgers: dict,
    cached_proj: Optional[Projection],
    fresh_proj_fetcher,
) -> int:
    # Step 1: resolve the bond holder. This is the only ledger that can burn stake.
    bond_domain = None
    for name, ledger in ledgers.items():
        if ledger.stake.get(agent, 0) > 0:
            bond_domain = name
            break
    if bond_domain is None:
        raise SlashAttributionError(
            f"no enforceable bond found for agent {agent!r} in any domain"
        )

    bond_ledger = ledgers[bond_domain]

    # Step 2: the cached projection is only usable if it is anchored to the bond domain
    # AND its epoch is not behind the bond domain's current epoch.
    proj = cached_proj
    if (
        proj is None
        or not proj.sig_valid
        or proj.source_domain != bond_domain
        or proj.bond_domain != bond_domain
        or proj.epoch < bond_ledger.epoch
    ):
        # Re-fetch at the bond domain's current epoch. If unavailable, defer.
        proj = fresh_proj_fetcher(agent, bond_domain, bond_ledger.epoch)
        if proj is None:
            raise SlashAttributionError(
                f"cannot anchor slash for {agent!r}: bond domain {bond_domain!r} "
                f"unreachable at epoch {bond_ledger.epoch}; defer to next epoch"
            )
        if proj.source_domain != bond_domain or proj.epoch < bond_ledger.epoch:
            raise SlashAttributionError(
                f"projection for {agent!r} not anchored to bond domain "
                f"{bond_domain!r} (source={proj.source_domain!r}, "
                f"proj_epoch={proj.epoch}, bond_epoch={bond_ledger.epoch})"
            )

    # Step 3: compute the effective slash against the anchored weight and burn stake.
    effective = int(round(bond_ledger.stake[agent] * (1.0 - proj.reputation * proj.weight)))
    effective = max(0, min(effective, bond_ledger.stake[agent]))
    bond_ledger.stake[agent] -= effective
    return effective
