"""Compliance score calculator (0–100), separate from risk score."""

from dataclasses import dataclass


@dataclass
class PenaltyBreakdown:
    """Per-severity penalty breakdown."""

    critical: int
    high: int
    medium: int
    low: int

    @property
    def total(self) -> int:
        return self.critical + self.high + self.medium + self.low


@dataclass
class ComplianceScore:
    """Compliance score result."""

    score: int  # 0–100
    trend: str  # "up" | "down" | "stable"
    penalty_breakdown: PenaltyBreakdown


def calculate_score(
    critical: int,
    high: int,
    medium: int,
    low: int,
    previous_score: int | None = None,
) -> ComplianceScore:
    """
    Calculate compliance score from finding counts.

    Formula:
        penalty = (critical × 30) + (high × 20) + (medium × 10) + (low × 5)
        score   = max(0, 100 − penalty)

    Trend vs previous score (±5 point threshold):
        up     — improved by ≥ 5 points
        down   — degraded by ≥ 5 points
        stable — delta < 5 points
    """
    penalty = (critical * 30) + (high * 20) + (medium * 10) + (low * 5)
    score = max(0, 100 - penalty)

    if previous_score is None:
        trend = "stable"
    else:
        delta = score - previous_score
        if delta >= 5:
            trend = "up"
        elif delta <= -5:
            trend = "down"
        else:
            trend = "stable"

    return ComplianceScore(
        score=score,
        trend=trend,
        penalty_breakdown=PenaltyBreakdown(
            critical=critical * 30,
            high=high * 20,
            medium=medium * 10,
            low=low * 5,
        ),
    )
