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

import typer

from ...telemetry import UnitMetricGenerator, UnitMetricsConfig
from ..common import (
    BaseCommand,
    display_summary_table,
    extract_date_range_from_files,
    group_files_by_prefix,
)


class UnitMetricsCommand(BaseCommand):
    """Unit metrics generation command."""

    def generate_metrics(
        self,
        org: str,
        config_file: Optional[str] = None,
        output_dir: Optional[str] = None,
        verbose: bool = False,
    ):
        """Generate unit metric data for an organization."""
        try:
            # Get organization directory
            org_dir = self.get_org_directory(org)

            # Determine config file path
            config_path = self.get_config_path(
                org_dir, config_file, "unit_metrics.yaml"
            )
            self.validate_file_exists(config_path, "unit metrics config file")

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

            config = UnitMetricsConfig.from_yaml(config_path)
            config.validate()

            # Determine output directory
            output_path = self.determine_output_directory(
                org_dir, output_dir, "unit_metrics"
            )

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

            all_created_files = []

            with self.create_progress_context() 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:
                        self.console.print(
                            f"[blue]Generated {len(created_files)} files for {metric_config.name}[/blue]"
                        )

                    progress.remove_task(task)

            # Display summary
            self._display_generation_summary(
                config.metrics, all_created_files, output_path
            )

        except Exception as e:
            self.handle_exception(e, "unit metrics generation", verbose)

    def validate_config(self, org: str, config_file: Optional[str] = None):
        """Validate unit metrics configuration file."""
        try:
            # Get organization directory
            org_dir = self.get_org_directory(org)

            # Determine config file path
            config_path = self.get_config_path(
                org_dir, config_file, "unit_metrics.yaml"
            )
            self.validate_file_exists(config_path, "unit metrics config file")

            # Load and validate configuration
            self.console.print(f"[blue]Validating configuration: {config_path}[/blue]")
            config = UnitMetricsConfig.from_yaml(config_path)
            config.validate()

            self.display_success(
                "Configuration is valid!",
                {
                    "Metrics defined": len(config.metrics),
                    "Config file": str(config_path),
                },
            )

            # Display metric summary
            self._display_metrics_table(config.metrics)

        except Exception as e:
            self.handle_exception(e, "unit metrics validation")

    def _display_metrics_table(self, metrics):
        """Display metrics summary table."""
        data = []
        for metric in metrics:
            data.append(
                {
                    "name": metric.name,
                    "scale": metric.scale.name,
                    "frequency": metric.frequency,
                    "range": f"{metric.start_date} to {metric.end_date}",
                }
            )

        display_summary_table(
            self.console,
            "Defined Metrics",
            data,
            ["name", "scale", "frequency", "range"],
        )

    def _display_generation_summary(self, metrics, created_files, output_path):
        """Display generation summary."""
        self.display_success(
            "Unit metrics generation completed!",
            {
                "Output directory": str(output_path),
                "Total files created": len(created_files),
            },
        )

        # Group files by metric
        metric_files = group_files_by_prefix(created_files)

        # Display file summary table
        data = []
        for metric_name, files in metric_files.items():
            data.append(
                {
                    "name": metric_name,
                    "files": len(files),
                    "range": extract_date_range_from_files(files),
                }
            )

        display_summary_table(
            self.console, "Generated Files", data, ["name", "files", "range"]
        )


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


@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."""
    unit_metrics_cmd.generate_metrics(org, config_file, output_dir, verbose)


@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."""
    unit_metrics_cmd.validate_config(org, config_file)
