"""关键词分析器.

提供关键词竞争度和价值分析功能。
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from src.keyword_research.google_planner import KeywordData


@dataclass
class KeywordScore:
    """关键词评分结果.

    Attributes:
        keyword: 关键词
        search_volume_score: 搜索量得分 (0-100)
        competition_score: 竞争度得分 (0-100，越高越好)
        value_score: 综合价值得分 (0-100)
        overall_score: 总体得分 (0-100)
        recommendation: 推荐等级 (high, medium, low)
    """

    keyword: str
    search_volume_score: float
    competition_score: float
    value_score: float
    overall_score: float
    recommendation: str


class KeywordAnalyzer:
    """关键词竞争度和价值分析器."""

    def __init__(self) -> None:
        """初始化分析器."""
        self.volume_weights = {
            "very_high": (10000, 100),
            "high": (1000, 80),
            "medium": (100, 60),
            "low": (10, 40),
            "very_low": (0, 20),
        }

    def calculate_volume_score(self, avg_monthly_searches: int) -> float:
        """计算搜索量得分."""
        for _tier, (threshold, score) in sorted(
            self.volume_weights.items(),
            key=lambda x: x[1][0],
            reverse=True,
        ):
            if avg_monthly_searches >= threshold:
                return float(score)
        return 0.0

    def calculate_competition_score(self, competition: str, cpc: float) -> float:
        """计算竞争度得分（越高竞争越好）."""
        competition_map = {"LOW": 80, "MEDIUM": 50, "HIGH": 20}
        base_score = competition_map.get(competition.upper(), 50)

        # CPC 调整
        if cpc < 1.0:
            cpc_adjustment = 10
        elif cpc < 3.0:
            cpc_adjustment = 0
        else:
            cpc_adjustment = -10

        return max(0, min(100, base_score + cpc_adjustment))

    def calculate_value_score(
        self, volume_score: float, competition_score: float, cpc: float
    ) -> float:
        """计算综合价值得分."""
        base_value = volume_score * 0.4 + competition_score * 0.4
        cpc_value = min(20, cpc * 5)
        return min(100, base_value + cpc_value)

    def analyze(self, data: KeywordData) -> KeywordScore:
        """分析单个关键词."""
        avg_cpc = (data.low_cpc + data.high_cpc) / 2

        volume_score = self.calculate_volume_score(data.avg_monthly_searches)
        competition_score = self.calculate_competition_score(data.competition, avg_cpc)
        value_score = self.calculate_value_score(volume_score, competition_score, avg_cpc)

        overall_score = volume_score * 0.3 + competition_score * 0.3 + value_score * 0.4

        if overall_score >= 70:
            recommendation = "high"
        elif overall_score >= 50:
            recommendation = "medium"
        else:
            recommendation = "low"

        return KeywordScore(
            keyword=data.keyword,
            search_volume_score=volume_score,
            competition_score=competition_score,
            value_score=value_score,
            overall_score=overall_score,
            recommendation=recommendation,
        )
