"""PlanitAI KPI - Main CLI entry point."""

from __future__ import annotations

import json
import sys
from pathlib import Path

import click

from src.config import Config
from src.sheets.client import GoogleSheetsClient, MockSheetsClient
from src.kpi.tree import KPITree
from src.kpi.calculator import KPICalculator
from src.kpi.analyzer import KPIAnalyzer
from src.ai.client import GeminiClient
from src.ai.analyzer import AIAnalyzer
from src.output.html import HTMLReportGenerator


@click.group()
@click.version_option(version="0.1.0")
def cli() -> None:
    """PlanitAI KPI - AI-powered KPI analysis tool."""
    pass


@cli.command()
@click.option(
    "--config", "-c",
    default="config.yaml",
    help="Path to configuration file.",
    type=click.Path(exists=True),
)
@click.option(
    "--period", "-p",
    required=True,
    help="Analysis period (e.g., '2024-11' or '2024年11月').",
)
@click.option(
    "--output", "-o",
    default="./output",
    help="Output directory for reports.",
    type=click.Path(),
)
@click.option(
    "--skip-ai",
    is_flag=True,
    help="Skip AI analysis (faster, for testing).",
)
@click.option(
    "--mock-data",
    type=click.Path(exists=True),
    help="Use mock data from JSON file instead of Google Sheets.",
)
def analyze(
    config: str,
    period: str,
    output: str,
    skip_ai: bool,
    mock_data: str | None,
) -> None:
    """Run KPI analysis and generate report."""
    click.echo("🚀 PlanitAI KPI Starting...")
    click.echo("")

    # Step 1: Load configuration
    click.echo("📁 Loading configuration...")
    try:
        cfg = Config.from_yaml(config)
        errors = cfg.validate(skip_ai=skip_ai or bool(mock_data))
        if errors:
            for error in errors:
                click.echo(f"  ❌ {error}", err=True)
            sys.exit(1)
        click.echo("  ✅ Configuration loaded")
    except Exception as e:
        click.echo(f"  ❌ Failed to load config: {e}", err=True)
        sys.exit(1)

    # Step 2: Get KPI data
    click.echo("📊 Fetching KPI data...")
    try:
        if mock_data:
            # Use mock data
            with open(mock_data) as f:
                data = json.load(f)
            actual_data = data.get("actual", {})
            target_data = data.get("target", {})
            click.echo(f"  ✅ Loaded mock data from {mock_data}")
        else:
            # Use Google Sheets
            sheets_client = GoogleSheetsClient(cfg.credentials_path)

            # Check if pivot format is enabled
            if cfg.sheet.pivot.enabled:
                pivot_config = {
                    "period_row": cfg.sheet.pivot.period_row,
                    "header_row": cfg.sheet.pivot.header_row,
                    "data_start_row": cfg.sheet.pivot.data_start_row,
                    "item_col": cfg.sheet.pivot.item_col,
                    "data_start_col": cfg.sheet.pivot.data_start_col,
                    "cols_per_period": cfg.sheet.pivot.cols_per_period,
                    "budget_col_offset": cfg.sheet.pivot.budget_col_offset,
                    "actual_col_offset": cfg.sheet.pivot.actual_col_offset,
                    "item_mapping": cfg.sheet.pivot.item_mapping,
                }
                actual_data, target_data = sheets_client.get_kpi_data(
                    sheet_id=cfg.sheet.sheet_id,
                    data_range=cfg.sheet.data_range,
                    pivot_format=True,
                    pivot_config=pivot_config,
                )
            else:
                actual_data, target_data = sheets_client.get_kpi_data(
                    sheet_id=cfg.sheet.sheet_id,
                    data_range=cfg.sheet.data_range,
                    target_range=cfg.sheet.target_range,
                    period_column=cfg.sheet.period_column,
                )
            click.echo(f"  ✅ Fetched data for {len(actual_data)} periods")

        if period not in actual_data:
            click.echo(f"  ⚠️ No data found for period: {period}")
            click.echo(f"  Available periods: {list(actual_data.keys())}")
            sys.exit(1)

    except Exception as e:
        click.echo(f"  ❌ Failed to fetch data: {e}", err=True)
        sys.exit(1)

    # Step 3: Build KPI tree
    click.echo("🌳 Building KPI tree...")
    try:
        tree = KPITree.from_config(cfg.tree)
        tree.set_values(actual_data[period])

        if period in target_data:
            tree.set_targets(target_data[period])

        validation_errors = tree.validate()
        if validation_errors:
            for error in validation_errors:
                click.echo(f"  ⚠️ {error}")

        click.echo(f"  ✅ Tree built with {len(tree.nodes)} nodes")
    except Exception as e:
        click.echo(f"  ❌ Failed to build tree: {e}", err=True)
        sys.exit(1)

    # Step 4: Calculate KPIs
    click.echo("🔢 Calculating KPIs...")
    try:
        calculator = KPICalculator(tree)
        results = calculator.calculate()
        click.echo(f"  ✅ Calculated {len(results)} KPIs")

        # Show KGI result
        kgi = tree.root
        if kgi.value is not None:
            achievement = kgi.achievement_rate
            achievement_str = f" ({achievement:.1f}%)" if achievement else ""
            click.echo(f"  📈 {kgi.name}: {kgi.value:,.0f} {kgi.unit}{achievement_str}")

    except Exception as e:
        click.echo(f"  ❌ Failed to calculate: {e}", err=True)
        sys.exit(1)

    # Step 5: AI Analysis
    analysis_results = {}
    if not skip_ai:
        click.echo("🤖 Running AI analysis...")
        try:
            if not cfg.gemini_api_key:
                click.echo("  ⚠️ No API key, skipping AI analysis")
            else:
                gemini_client = GeminiClient(cfg.gemini_api_key)
                ai_analyzer = AIAnalyzer(gemini_client, tree)

                click.echo("  ⏳ Analyzing trends...")
                analysis_results["trends"] = ai_analyzer.analyze_trends(period)

                click.echo("  ⏳ Analyzing bottlenecks...")
                analysis_results["bottlenecks"] = ai_analyzer.analyze_bottlenecks()

                click.echo("  ⏳ Generating executive summary...")
                analysis_results["executive_summary"] = ai_analyzer.generate_executive_summary(period)

                click.echo("  ✅ AI analysis complete")

        except Exception as e:
            click.echo(f"  ⚠️ AI analysis failed: {e}")
            click.echo("  Continuing without AI insights...")
    else:
        click.echo("⏭️ Skipping AI analysis (--skip-ai)")

    # Step 6: Generate report
    click.echo("📝 Generating report...")
    try:
        generator = HTMLReportGenerator()
        output_path = generator.generate(
            tree=tree,
            analysis_results=analysis_results,
            period=period,
            output_path=output,
            title=f"KPI Report - {period}",
        )
        click.echo(f"  ✅ Report generated: {output_path}")

    except Exception as e:
        click.echo(f"  ❌ Failed to generate report: {e}", err=True)
        sys.exit(1)

    click.echo("")
    click.echo("✨ Analysis complete!")
    click.echo(f"   Open {output_path} in your browser to view the report.")


@cli.command()
@click.option(
    "--config", "-c",
    default="config.yaml",
    help="Path to configuration file.",
    type=click.Path(exists=True),
)
def validate(config: str) -> None:
    """Validate configuration file."""
    click.echo("🔍 Validating configuration...")

    try:
        cfg = Config.from_yaml(config)
        errors = cfg.validate()

        if errors:
            click.echo("❌ Validation failed:")
            for error in errors:
                click.echo(f"   - {error}")
            sys.exit(1)
        else:
            click.echo("✅ Configuration is valid!")
            click.echo(f"   - {len(cfg.tree)} KPI nodes defined")
            click.echo(f"   - Sheet ID: {cfg.sheet.sheet_id[:20]}...")

    except Exception as e:
        click.echo(f"❌ Failed to load config: {e}", err=True)
        sys.exit(1)


@cli.command()
@click.option(
    "--config", "-c",
    default="config.yaml",
    help="Path to configuration file.",
    type=click.Path(exists=True),
)
def tree(config: str) -> None:
    """Display KPI tree structure."""
    try:
        cfg = Config.from_yaml(config)
        kpi_tree = KPITree.from_config(cfg.tree)

        click.echo("🌳 KPI Tree Structure:")
        click.echo("")
        click.echo(kpi_tree.to_text())

    except Exception as e:
        click.echo(f"❌ Failed: {e}", err=True)
        sys.exit(1)


@cli.command()
@click.option(
    "--output", "-o",
    default="config.yaml",
    help="Output file path.",
    type=click.Path(),
)
def init(output: str) -> None:
    """Create example configuration file."""
    example_config = """# PlanitAI KPI Configuration

# Google Sheets Settings
sheet:
  sheet_id: "YOUR_SHEET_ID_HERE"
  data_range: "Sheet1!A1:Z100"
  target_range: "Targets!A1:Z100"  # Optional
  period_column: "period"

# Gemini API Key (use environment variable)
gemini_api_key: "${GEMINI_API_KEY}"

# Output Settings
output_path: "./output"
language: "ja"

# Credentials file for Google Sheets
credentials_path: "credentials.json"

# KPI Tree Definition
tree:
  # KGI (Key Goal Indicator) - Top level
  - id: revenue
    name: 月間売上
    type: kgi
    formula: "{contracts} * {avg_price}"
    unit: 円
    category: finance
    children: [contracts, avg_price]

  # KPI (Key Performance Indicator) - Calculated metrics
  - id: contracts
    name: 契約数
    type: kpi
    formula: "{meetings} * {close_rate}"
    unit: 件
    category: sales
    children: [meetings, close_rate]

  - id: meetings
    name: 商談数
    type: kpi
    formula: "{leads} * {meeting_rate}"
    unit: 件
    category: sales
    children: [leads, meeting_rate]

  # INPUT - Leaf nodes (manually entered values)
  - id: avg_price
    name: 平均単価
    type: input
    unit: 円
    category: finance

  - id: close_rate
    name: 成約率
    type: input
    unit: "%"
    category: sales

  - id: leads
    name: リード数
    type: input
    unit: 件
    category: marketing

  - id: meeting_rate
    name: 商談化率
    type: input
    unit: "%"
    category: marketing
"""

    path = Path(output)
    if path.exists():
        if not click.confirm(f"'{output}' already exists. Overwrite?"):
            click.echo("Cancelled.")
            return

    with open(path, "w", encoding="utf-8") as f:
        f.write(example_config)

    click.echo(f"✅ Created example configuration: {output}")
    click.echo("")
    click.echo("Next steps:")
    click.echo("  1. Update 'sheet_id' with your Google Sheets ID")
    click.echo("  2. Set GEMINI_API_KEY environment variable")
    click.echo("  3. Place your 'credentials.json' (Google service account)")
    click.echo("  4. Customize the KPI tree for your business")
    click.echo("")
    click.echo("Then run: planitai-kpi analyze -p '2024-11'")


def main() -> None:
    """Main entry point."""
    cli()


if __name__ == "__main__":
    main()
