from typing import Optional
"""Unit metrics CLI commands."""

import typer
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.table import Table

from ..telemetry import UnitMetricGenerator, UnitMetricsConfig
from .common.base import BaseCommand


class UnitMetricsCommand(BaseCommand):
    """Unit metrics command with service integration."""

    def __init__(self):
        super().__init__()

    def load_telemetry_config(
        self, org_name: str, config_file: Optional[str] = None
    ) -> dict:
        """Load telemetry configuration using ConfigurationService."""
        from src.services.configuration import ConfigurationService

        org_dir = self.get_org_directory(org_name)
        config_service = ConfigurationService(org_dir)

        # Load unit metrics config
        return config_service.load_unit_metrics_config(config_file)


unit_metrics_cmd = UnitMetricsCommand()
app = typer.Typer(help="Unit metrics generation commands")


@app.command()
def generate(
    org: str = typer.Argument(..., help="Organization name"),
    config_file: Optional[str] = typer.Option(
        None, "--config", "-c", help="Custom unit metrics config file path"
    ),
    output_dir: Optional[str] = typer.Option(
        None, "--output", "-o", help="Custom output directory path"
    ),
    verbose: bool = typer.Option(
        False, "--verbose", "-v", help="Enable verbose output"
    ),
):
    """Generate unit metric data for an organization."""

    try:
        # Load telemetry configuration using services
        try:
            config_data = unit_metrics_cmd.load_telemetry_config(org, config_file)
            config_source = f"telemetry/configs/{config_file or 'unit_metrics'}.yaml"
        except FileNotFoundError as e:
            unit_metrics_cmd.console.print(
                f"[red]Unit metrics config not found: {e}[/red]"
            )
            unit_metrics_cmd.console.print(
                "[yellow]Expected location: telemetry/configs/unit_metrics.yaml[/yellow]"
            )
            raise typer.Exit(1)

        # Load configuration
        if verbose:
            unit_metrics_cmd.console.print(
                f"[blue]Loading configuration from: {config_source}[/blue]"
            )

        config = UnitMetricsConfig.from_dict(config_data)
        config.validate()

        # Determine output directory using BaseCommand
        output_path = unit_metrics_cmd.determine_output_directory(
            org_name=org,
            output_dir=output_dir,
            subdir="unit_metrics",
            run_type="telemetry",
        )

        # Generate metrics
        unit_metrics_cmd.console.print(
            f"[green]Generating {len(config.metrics)} unit metrics...[/green]"
        )

        all_created_files = []

        with Progress(
            SpinnerColumn(),
            TextColumn("[progress.description]{task.description}"),
            console=unit_metrics_cmd.console,
            transient=True,
        ) as progress:
            for metric_config in config.metrics:
                task = progress.add_task(
                    f"Generating {metric_config.name}...", total=None
                )

                # Generate metric data
                generator = UnitMetricGenerator(metric_config)
                created_files = generator.generate_monthly_files(output_path)
                all_created_files.extend(created_files)

                if verbose:
                    unit_metrics_cmd.console.print(
                        f"[blue]Generated {len(created_files)} files for {metric_config.name}[/blue]"
                    )

                progress.remove_task(task)

        # Display summary
        _display_summary(config.metrics, all_created_files, output_path)

    except Exception as e:
        unit_metrics_cmd.console.print(
            f"[red]Error generating unit metrics: {str(e)}[/red]"
        )
        if verbose:
            unit_metrics_cmd.console.print_exception()
        raise typer.Exit(1)


@app.command()
def validate(
    org: str = typer.Argument(..., help="Organization name"),
    config_file: Optional[str] = typer.Option(
        None, "--config", "-c", help="Custom unit metrics config file path"
    ),
):
    """Validate unit metrics configuration file."""

    try:
        # Load telemetry configuration using services
        try:
            config_data = unit_metrics_cmd.load_telemetry_config(org, config_file)
            config_source = f"telemetry/configs/{config_file or 'unit_metrics'}.yaml"
        except FileNotFoundError as e:
            unit_metrics_cmd.console.print(
                f"[red]Unit metrics config not found: {e}[/red]"
            )
            raise typer.Exit(1)

        # Load and validate configuration
        unit_metrics_cmd.console.print(
            f"[blue]Validating configuration: {config_source}[/blue]"
        )
        config = UnitMetricsConfig.from_dict(config_data)
        config.validate()

        unit_metrics_cmd.console.print("[green]✓ Configuration is valid![/green]")
        unit_metrics_cmd.console.print(
            f"[blue]Found {len(config.metrics)} metric(s) defined[/blue]"
        )

        # Display metric summary
        table = Table(title="Defined Metrics")
        table.add_column("Name", style="cyan")
        table.add_column("Scale", style="magenta")
        table.add_column("Frequency", style="green")
        table.add_column("Date Range", style="yellow")

        for metric in config.metrics:
            date_range = f"{metric.start_date} to {metric.end_date}"
            table.add_row(metric.name, metric.scale.name, metric.frequency, date_range)

        unit_metrics_cmd.console.print(table)

    except Exception as e:
        unit_metrics_cmd.console.print(f"[red]Validation failed: {str(e)}[/red]")
        raise typer.Exit(1)


def _display_summary(metrics, created_files, output_path):
    """Display generation summary."""
    unit_metrics_cmd.console.print(
        "\n[green]✓ Unit metrics generation completed![/green]"
    )
    unit_metrics_cmd.console.print(f"[blue]Output directory: {output_path}[/blue]")
    unit_metrics_cmd.console.print(
        f"[blue]Total files created: {len(created_files)}[/blue]"
    )

    # Group files by metric
    metric_files = {}
    for file_path in created_files:
        metric_name = file_path.stem.rsplit("_", 1)[0]  # Remove date suffix
        if metric_name not in metric_files:
            metric_files[metric_name] = []
        metric_files[metric_name].append(file_path)

    # Display file summary table
    table = Table(title="Generated Files")
    table.add_column("Metric", style="cyan")
    table.add_column("Files", style="magenta")
    table.add_column("Date Range", style="green")

    for metric_name, files in metric_files.items():
        file_count = len(files)

        # Extract date range from filenames
        dates = []
        for file_path in files:
            date_part = file_path.stem.split("_")[-1]  # Get date part
            dates.append(date_part)

        date_range = f"{min(dates)} to {max(dates)}" if dates else "N/A"

        table.add_row(metric_name, str(file_count), date_range)

    unit_metrics_cmd.console.print(table)
