"""Computes landed cost and the recommended selling price for a SKU."""
from __future__ import annotations

from dataclasses import dataclass

from ....utils.helpers import round2


@dataclass
class PricingResult:
    supplier_cost: float
    shipping_cost: float
    total_cost: float
    profit_margin_target: float          # markup requested by the business owner (%)
    recommended_selling_price: float
    estimated_profit: float
    margin: float                        # realized margin on the selling price (%)

    def to_dict(self) -> dict:
        return {
            "supplierPrice": self.supplier_cost,
            "shipping": self.shipping_cost,
            "totalCost": self.total_cost,
            "profitMargin": self.profit_margin_target,
            "recommendedSellingPrice": self.recommended_selling_price,
            "estimatedProfit": self.estimated_profit,
            "realizedMargin": self.margin,
        }


class PricingAnalyzer:
    """Single responsibility: pricing arithmetic.

    Business rule: the owner-provided ``profitMargin`` is a markup applied to
    the total landed cost:

        selling_price = (supplier + shipping) * (1 + margin / 100)

    ``margin`` in the result is the realized margin relative to the selling
    price, which is the number an accountant would report.
    """

    def analyze(
        self,
        supplier_price: float,
        shipping_price: float,
        profit_margin: float,
    ) -> PricingResult:
        supplier_cost = round2(supplier_price)
        shipping_cost = round2(shipping_price)
        total_cost = round2(supplier_cost + shipping_cost)

        selling_price = round2(total_cost * (1 + profit_margin / 100.0))
        estimated_profit = round2(selling_price - total_cost)
        realized_margin = (
            round2((estimated_profit / selling_price) * 100.0)
            if selling_price > 0
            else 0.0
        )

        return PricingResult(
            supplier_cost=supplier_cost,
            shipping_cost=shipping_cost,
            total_cost=total_cost,
            profit_margin_target=round2(profit_margin),
            recommended_selling_price=selling_price,
            estimated_profit=estimated_profit,
            margin=realized_margin,
        )
