from __future__ import annotations

from collections import Counter
from dataclasses import dataclass
from decimal import Decimal


@dataclass(frozen=True)
class TradeRecord:
    coin: str


@dataclass(frozen=True)
class CoinLeakageDecision:
    allowed: bool
    risk_multiplier: Decimal
    top_coin: str | None
    top_coin_share: Decimal
    reason: str = "ok"


@dataclass(frozen=True)
class CoinLeakageGate:
    reduce_threshold: float = 0.50
    block_threshold: float = 0.60
    reduced_multiplier: float = 0.25

    def evaluate(self, coin: str, trades: list[TradeRecord], *, window: int) -> CoinLeakageDecision:
        recent = trades[-window:]
        if not recent:
            return CoinLeakageDecision(True, Decimal("1"), None, Decimal("0"))
        counts = Counter(record.coin.upper() for record in recent)
        top_coin, top_count = counts.most_common(1)[0]
        share = Decimal(top_count) / Decimal(len(recent))
        coin = coin.upper()
        if coin == top_coin and share > Decimal(str(self.block_threshold)):
            return CoinLeakageDecision(False, Decimal("0"), top_coin, share, "coin_leakage_block")
        if coin == top_coin and share > Decimal(str(self.reduce_threshold)):
            return CoinLeakageDecision(True, Decimal(str(self.reduced_multiplier)), top_coin, share, "coin_leakage_reduce")
        return CoinLeakageDecision(True, Decimal("1"), top_coin, share)
