"""Scores the profitability of a SKU."""
from __future__ import annotations

from dataclasses import dataclass

from ....constants import constants as C
from ....utils.helpers import clamp, ratio_score, round2

from .pricing_analyzer import PricingResult


@dataclass
class ProfitAnalysis:
    estimated_profit: float
    margin: float                 # realized margin (%)
    roi: float                    # profit / total cost (%)
    price_competitiveness: float  # 0-100, recommended price vs. AliExpress list price
    score: float                  # 0-100

    def to_dict(self) -> dict:
        return {
            "estimatedProfit": self.estimated_profit,
            "margin": self.margin,
            "roi": self.roi,
            "priceCompetitiveness": round(self.price_competitiveness, 2),
            "score": round(self.score, 2),
        }


class ProfitAnalyzer:
    """Single responsibility: profitability metrics and score."""

    def analyze(self, pricing: PricingResult, market_reference_price: float) -> ProfitAnalysis:
        roi = (
            round2((pricing.estimated_profit / pricing.total_cost) * 100.0)
            if pricing.total_cost > 0
            else 0.0
        )
        competitiveness = self._price_competitiveness(
            pricing.recommended_selling_price, market_reference_price
        )

        weights = C.PROFIT_SCORE_WEIGHTS
        score = clamp(
            ratio_score(roi, C.ROI_FOR_FULL_SCORE) * weights["roi"]
            + ratio_score(pricing.margin, C.MARGIN_FOR_FULL_SCORE) * weights["margin"]
            + ratio_score(pricing.estimated_profit, C.PROFIT_FOR_FULL_SCORE)
            * weights["absolute_profit"]
            + competitiveness * weights["price_competitiveness"]
        )

        return ProfitAnalysis(
            estimated_profit=pricing.estimated_profit,
            margin=pricing.margin,
            roi=roi,
            price_competitiveness=competitiveness,
            score=score,
        )

    # ------------------------------------------------------------------ #
    @staticmethod
    def _price_competitiveness(recommended_price: float, reference_price: float) -> float:
        """How the recommended price compares to the AliExpress list price.

        A recommended price at or below the reference retail price is fully
        competitive (100). Twice the reference price scores 0.
        """
        if reference_price <= 0 or recommended_price <= 0:
            return 50.0  # unknown reference: neutral
        ratio = recommended_price / reference_price
        if ratio <= 1.0:
            return 100.0
        return clamp((2.0 - ratio) * 100.0)
