"""Identifies business strengths in the product / store / SKU data.

Each strength signal carries its own weight (see ``STRENGTH_SIGNAL_POINTS``)
covering listing quality (description, images, specifications), supplier
quality, shipping quality and commercial signals. A complete, well-rated,
fast-shipping listing typically scores 65-85.
"""
from __future__ import annotations

from dataclasses import dataclass, field

from ...constants import constants as C
from ...utils.helpers import clamp

from .product_analyzer import ProductAnalysis
from .store_analyzer import StoreAnalysis
from .sku.sku_decision_engine import SkuDecision


@dataclass
class StrengthAnalysis:
    score: float                       # 0-100, higher = stronger
    strengths: list[str] = field(default_factory=list)

    def to_dict(self) -> dict:
        return {"score": round(self.score, 2), "strengths": self.strengths}


class StrengthAnalyzer:
    """Single responsibility: enumerate weighted strength signals."""

    def analyze(
        self,
        product: ProductAnalysis,
        store: StoreAnalysis,
        sku_decisions: list[SkuDecision],
    ) -> StrengthAnalysis:
        points = C.STRENGTH_SIGNAL_POINTS
        best = max(sku_decisions, key=lambda d: d.result.score) if sku_decisions else None
        total_stock = sum(d.sku.stock for d in sku_decisions)
        rating = product.average_rating or store.average_rating

        strengths: list[str] = []
        score = 0.0

        def add(signal: str, reason: str) -> None:
            nonlocal score
            strengths.append(reason)
            score += points[signal]

        # --- Review / rating quality -----------------------------------
        if rating >= C.STRENGTH_HIGH_RATING:
            add("high_rating", f"High rating: {rating:.1f}/5")
        elif rating >= C.STRENGTH_DECENT_RATING:
            add("decent_rating", f"Positive rating: {rating:.1f}/5")

        # --- Sales history ----------------------------------------------
        if product.sales_count >= C.STRENGTH_HIGH_SALES:
            add("high_sales", f"Proven sales history: {product.sales_count} orders")
        elif product.sales_count >= C.STRENGTH_SOME_SALES:
            add("some_sales", f"Moderate sales history: {product.sales_count} orders")

        # --- Supplier quality --------------------------------------------
        if store.score >= C.STRENGTH_TRUSTED_STORE_SCORE:
            add("trusted_store",
                f"Trusted store: {store.grade} grade ({store.score:.0f}/100)")

        # --- Shipping quality --------------------------------------------
        if best and (best.freight.delivery_days_max or 999) <= C.STRENGTH_FAST_SHIPPING_DAYS:
            add("fast_shipping",
                f"Fast shipping: delivered within {best.freight.delivery_days_max} days")
        if best and best.freight.tracking:
            add("tracking", "Tracked shipping available")

        # --- Inventory / range ---------------------------------------------
        if total_stock >= C.STRENGTH_HEALTHY_STOCK_UNITS:
            add("healthy_stock", f"Healthy stock: {total_stock} units across all SKUs")
        if len(sku_decisions) >= C.STRENGTH_MANY_VARIANTS:
            add("many_variants", f"Many variants: {len(sku_decisions)} SKUs to offer")

        # --- Pricing --------------------------------------------------------
        if best and 0 < best.sku.supplier_price <= C.STRENGTH_GOOD_PRICE:
            add("good_price",
                f"Good supplier price: {best.sku.supplier_price:.2f} for the best SKU")

        # --- Listing quality (previously not counted) -----------------------
        if product.description_length >= C.STRENGTH_COMPLETE_DESCRIPTION:
            add("complete_description", "Complete product description")
        if product.image_count >= C.STRENGTH_MULTIPLE_IMAGES:
            add("multiple_images", f"Multiple product images ({product.image_count})")
        if product.property_count >= C.STRENGTH_GOOD_SPECIFICATIONS:
            add("good_specifications",
                f"Detailed specifications ({product.property_count} properties)")

        return StrengthAnalysis(score=clamp(score), strengths=strengths)
