"""Prompt templates for AI analysis."""

from __future__ import annotations

from dataclasses import dataclass
from string import Template


@dataclass
class PromptTemplate:
    """Reusable prompt template."""

    template: str
    required_vars: list[str]

    def render(self, **kwargs: str) -> str:
        """Render template with variables.

        Args:
            **kwargs: Template variables.

        Returns:
            Rendered prompt string.

        Raises:
            ValueError: If required variables are missing.
        """
        missing = set(self.required_vars) - set(kwargs.keys())
        if missing:
            raise ValueError(f"Missing required variables: {missing}")

        return Template(self.template).safe_substitute(**kwargs)


class PromptLibrary:
    """Library of prompt templates for KPI analysis."""

    SYSTEM_PROMPT = """あなたは企業のKPI分析の専門家です。
以下の役割を担当します：

1. データ分析: KPIデータを分析し、傾向やパターンを特定
2. 問題発見: ボトルネックや異常値を検出
3. 改善提案: 具体的で実行可能な改善策を提案
4. 予測: 将来のパフォーマンスを予測

回答のルール：
- 数値は具体的に記載（例：前月比+15.3%）
- 日本語で回答
- 経営層にも分かりやすい表現を使用
- 提案は優先順位をつけて記載
- JSON形式で構造化して回答"""

    TREND_ANALYSIS = PromptTemplate(
        template="""## KPIトレンド分析依頼

### 分析対象期間
$period

### KPIツリー構造
$tree_structure

### 実績データ
```json
$performance_data
```

### 分析してほしいこと
1. 各KPIの推移傾向（上昇/安定/下降）
2. 目標達成率の評価
3. 特に注目すべき変化
4. KPI間の相関関係

### 出力形式
以下のJSON形式で回答してください：
```json
{
  "summary": "全体サマリー（2-3文）",
  "trends": [
    {
      "kpi_id": "KPI ID",
      "kpi_name": "KPI名",
      "trend": "improving/stable/declining",
      "change_rate": "変化率（例：+15%）",
      "insight": "具体的なインサイト"
    }
  ],
  "highlights": ["注目ポイント1", "注目ポイント2", "注目ポイント3"],
  "correlations": [
    {
      "kpi_a": "KPI A",
      "kpi_b": "KPI B",
      "relationship": "相関関係の説明"
    }
  ]
}
```""",
        required_vars=["period", "tree_structure", "performance_data"],
    )

    BOTTLENECK_ANALYSIS = PromptTemplate(
        template="""## ボトルネック分析依頼

### 現状
KGI「$kgi_name」の達成率: $achievement_rate%

### 各KPIの達成状況
```json
$performance_data
```

### KPIツリー構造
$tree_structure

### 特定されたボトルネック
```json
$bottleneck_data
```

### 分析してほしいこと
1. KGI未達の主要原因となっているKPI
2. 各ボトルネックの影響度
3. 改善の優先順位
4. 具体的な改善アクション

### 出力形式
```json
{
  "summary": "ボトルネック分析サマリー（2-3文）",
  "root_causes": [
    {
      "kpi_id": "KPI ID",
      "kpi_name": "KPI名",
      "impact": "high/medium/low",
      "cause_analysis": "原因分析",
      "recommended_actions": ["アクション1", "アクション2"]
    }
  ],
  "priority_order": ["最優先KPI ID", "次優先KPI ID"],
  "quick_wins": ["すぐに実行できる施策"],
  "strategic_initiatives": ["中長期的な取り組み"]
}
```""",
        required_vars=[
            "kgi_name",
            "achievement_rate",
            "performance_data",
            "tree_structure",
            "bottleneck_data",
        ],
    )

    EXECUTIVE_SUMMARY = PromptTemplate(
        template="""## エグゼクティブサマリー作成依頼

### 報告対象期間
$period

### KGI達成状況
$kgi_summary

### 各KPIの達成状況
```json
$performance_data
```

### カテゴリ別サマリー
```json
$category_summary
```

### ボトルネック情報
```json
$bottleneck_data
```

### 作成してほしいもの
経営層向けのエグゼクティブサマリーを作成してください。

要件：
- 3分で読める長さ
- 数字を明確に
- 課題と対策をセットで
- アクションアイテムを明確に

### 出力形式
```json
{
  "headline": "今月の一言（20字以内）",
  "performance_overview": "全体パフォーマンス概要（3-4文）",
  "highlights": [
    {"type": "positive/negative/neutral", "content": "ハイライト内容"}
  ],
  "key_metrics": [
    {"name": "指標名", "value": "値", "vs_target": "対目標", "status": "good/warning/critical"}
  ],
  "issues_and_actions": [
    {"issue": "課題", "action": "対策", "priority": "high/medium/low"}
  ],
  "next_month_focus": ["来月の重点項目"]
}
```""",
        required_vars=[
            "period",
            "kgi_summary",
            "performance_data",
            "category_summary",
            "bottleneck_data",
        ],
    )

    IMPROVEMENT_SUGGESTIONS = PromptTemplate(
        template="""## 改善提案依頼

### 対象KPI
- ID: $kpi_id
- 名前: $kpi_name
- 現在値: $current_value
- 目標値: $target_value
- 達成率: $achievement_rate%

### KPIの位置づけ
$kpi_context

### 過去のトレンド
$historical_trend

### 改善提案を作成してください
具体的で実行可能な改善提案を3-5つ提示してください。

### 出力形式
```json
{
  "analysis": "現状分析（2-3文）",
  "suggestions": [
    {
      "title": "提案タイトル",
      "description": "詳細説明",
      "expected_impact": "期待効果（数値で）",
      "effort": "high/medium/low",
      "timeline": "実行期間"
    }
  ],
  "recommended_target": "推奨される目標値調整（あれば）"
}
```""",
        required_vars=[
            "kpi_id",
            "kpi_name",
            "current_value",
            "target_value",
            "achievement_rate",
            "kpi_context",
            "historical_trend",
        ],
    )
