"""Risk-based sampling strategy for audit review and replay."""

from __future__ import annotations

from dataclasses import dataclass
from decimal import Decimal
from typing import Any

from .models import RiskHistoryStats


@dataclass(slots=True)
class RiskSamplingDecision:
    strategy: str
    threshold: int
    replay_bucket: str
    audit_required: bool
    reason: str

    def as_dict(self) -> dict[str, Any]:
        return {
            "strategy": self.strategy,
            "threshold": self.threshold,
            "replay_bucket": self.replay_bucket,
            "audit_required": self.audit_required,
            "reason": self.reason,
        }


class RiskSamplingPlanner:
    def plan(
        self,
        *,
        risk_score: int,
        confidence: Decimal,
        evidence_source_count: int,
        data_quality_passed: bool = True,
        data_quality_gate: str = "",
        history: RiskHistoryStats | None = None,
    ) -> RiskSamplingDecision:
        false_positive_rate = _false_positive_rate(history)
        if not data_quality_passed:
            return RiskSamplingDecision(
                strategy="uncertainty_sample",
                threshold=45,
                replay_bucket="data_quality_gate",
                audit_required=True,
                reason=data_quality_gate or "data_quality_gate_not_passed",
            )
        if risk_score >= 90:
            return RiskSamplingDecision(
                strategy="mandatory_review",
                threshold=90,
                replay_bucket="critical_high_risk",
                audit_required=True,
                reason="risk_score_above_critical_threshold",
            )
        if risk_score >= 70:
            return RiskSamplingDecision(
                strategy="focused_review",
                threshold=70,
                replay_bucket="high_risk",
                audit_required=True,
                reason="risk_score_above_high_threshold",
            )
        if false_positive_rate >= Decimal("0.30"):
            return RiskSamplingDecision(
                strategy="calibration_sample",
                threshold=45,
                replay_bucket="false_positive_calibration",
                audit_required=True,
                reason="historical_false_positive_rate_high",
            )
        if confidence < Decimal("0.55") or evidence_source_count < 2:
            return RiskSamplingDecision(
                strategy="uncertainty_sample",
                threshold=45,
                replay_bucket="low_confidence",
                audit_required=True,
                reason="confidence_or_evidence_source_insufficient",
            )
        return RiskSamplingDecision(
            strategy="monitor",
            threshold=31,
            replay_bucket="routine_monitoring",
            audit_required=False,
            reason="below_review_threshold",
        )


def _false_positive_rate(history: RiskHistoryStats | None) -> Decimal:
    if history is None or history.similar_case_count <= 0:
        return Decimal("0")
    return Decimal(history.false_positive_count) / Decimal(history.similar_case_count)
