"""AI-powered KPI analyzer."""

from __future__ import annotations

import json
from dataclasses import dataclass, field
from typing import Any

from .client import GeminiClient
from .prompts import PromptLibrary
from src.kpi.tree import KPITree
from src.kpi.analyzer import KPIAnalyzer, BottleneckInfo, PerformanceInfo


@dataclass
class AnalysisResult:
    """Result of AI analysis."""

    analysis_type: str
    summary: str
    data: dict[str, Any]
    confidence: float = 0.85
    raw_response: dict[str, Any] = field(default_factory=dict)

    def to_dict(self) -> dict[str, Any]:
        """Convert to dictionary."""
        return {
            "analysis_type": self.analysis_type,
            "summary": self.summary,
            "data": self.data,
            "confidence": self.confidence,
        }


class AIAnalyzer:
    """AI-powered analyzer for KPIs using Gemini."""

    def __init__(self, client: GeminiClient, tree: KPITree):
        """Initialize AI analyzer.

        Args:
            client: Gemini client.
            tree: KPI tree to analyze.
        """
        self.client = client
        self.tree = tree
        self.kpi_analyzer = KPIAnalyzer(tree)
        self.prompts = PromptLibrary

    def analyze_trends(self, period: str) -> AnalysisResult:
        """Analyze KPI trends.

        Args:
            period: Analysis period string.

        Returns:
            Analysis result with trend insights.
        """
        # Prepare data
        performance_data = [p.to_dict() for p in self.kpi_analyzer.get_performance_summary()]

        # Build prompt
        prompt = self.prompts.TREND_ANALYSIS.render(
            period=period,
            tree_structure=self.tree.to_text(),
            performance_data=json.dumps(performance_data, ensure_ascii=False, indent=2),
        )

        # Generate analysis
        response = self.client.generate_json(
            prompt=prompt,
            system_prompt=self.prompts.SYSTEM_PROMPT,
        )

        summary = response.get("summary", "トレンド分析を完了しました。")

        return AnalysisResult(
            analysis_type="trend",
            summary=summary,
            data={
                "trends": response.get("trends", []),
                "highlights": response.get("highlights", []),
                "correlations": response.get("correlations", []),
            },
            raw_response=response,
        )

    def analyze_bottlenecks(self) -> AnalysisResult:
        """Analyze KPI bottlenecks.

        Returns:
            Analysis result with bottleneck insights.
        """
        # Get KGI info
        kgi_summary = self.kpi_analyzer.get_kgi_summary()
        kgi_name = kgi_summary.get("name", "KGI")
        achievement_rate = kgi_summary.get("achievement_rate", 0) or 0

        # Get bottlenecks
        bottlenecks = self.kpi_analyzer.find_bottlenecks()
        bottleneck_data = [b.to_dict() for b in bottlenecks]

        # Get performance data
        performance_data = [p.to_dict() for p in self.kpi_analyzer.get_performance_summary()]

        # Build prompt
        prompt = self.prompts.BOTTLENECK_ANALYSIS.render(
            kgi_name=kgi_name,
            achievement_rate=f"{achievement_rate:.1f}",
            performance_data=json.dumps(performance_data, ensure_ascii=False, indent=2),
            tree_structure=self.tree.to_text(),
            bottleneck_data=json.dumps(bottleneck_data, ensure_ascii=False, indent=2),
        )

        # Generate analysis
        response = self.client.generate_json(
            prompt=prompt,
            system_prompt=self.prompts.SYSTEM_PROMPT,
        )

        summary = response.get("summary", f"ボトルネック分析を完了しました。{len(bottlenecks)}件の課題を特定。")

        return AnalysisResult(
            analysis_type="bottleneck",
            summary=summary,
            data={
                "root_causes": response.get("root_causes", []),
                "priority_order": response.get("priority_order", []),
                "quick_wins": response.get("quick_wins", []),
                "strategic_initiatives": response.get("strategic_initiatives", []),
                "detected_bottlenecks": bottleneck_data,
            },
            raw_response=response,
        )

    def generate_executive_summary(self, period: str) -> AnalysisResult:
        """Generate executive summary.

        Args:
            period: Reporting period.

        Returns:
            Analysis result with executive summary.
        """
        # Gather all data
        kgi_summary = self.kpi_analyzer.get_kgi_summary()
        performance_data = [p.to_dict() for p in self.kpi_analyzer.get_performance_summary()]
        category_summary = self.kpi_analyzer.get_category_summary()
        bottlenecks = self.kpi_analyzer.find_bottlenecks()
        bottleneck_data = [b.to_dict() for b in bottlenecks[:5]]  # Top 5

        # Build prompt
        prompt = self.prompts.EXECUTIVE_SUMMARY.render(
            period=period,
            kgi_summary=json.dumps(kgi_summary, ensure_ascii=False, indent=2),
            performance_data=json.dumps(performance_data, ensure_ascii=False, indent=2),
            category_summary=json.dumps(category_summary, ensure_ascii=False, indent=2),
            bottleneck_data=json.dumps(bottleneck_data, ensure_ascii=False, indent=2),
        )

        # Generate analysis
        response = self.client.generate_json(
            prompt=prompt,
            system_prompt=self.prompts.SYSTEM_PROMPT,
        )

        headline = response.get("headline", "KPI分析レポート")
        overview = response.get("performance_overview", "")
        summary = f"{headline}: {overview[:100]}..." if len(overview) > 100 else f"{headline}: {overview}"

        return AnalysisResult(
            analysis_type="executive_summary",
            summary=summary,
            data={
                "headline": headline,
                "performance_overview": overview,
                "highlights": response.get("highlights", []),
                "key_metrics": response.get("key_metrics", []),
                "issues_and_actions": response.get("issues_and_actions", []),
                "next_month_focus": response.get("next_month_focus", []),
            },
            confidence=0.90,
            raw_response=response,
        )

    def get_full_analysis(self, period: str) -> dict[str, AnalysisResult]:
        """Run all analyses.

        Args:
            period: Analysis period.

        Returns:
            Dictionary mapping analysis type to result.
        """
        return {
            "trends": self.analyze_trends(period),
            "bottlenecks": self.analyze_bottlenecks(),
            "executive_summary": self.generate_executive_summary(period),
        }
