from typing import Optional
"""
Reference data usage analysis commands.
"""

from pathlib import Path

import polars as pl
import typer

from ..common import BaseCommand, display_summary_table


class ReferenceUsageCommand(BaseCommand):
    """Reference data usage analysis command."""

    def analyze_usage(
        self,
        file_path: str,
        provider: Optional[str] = None,
        service: Optional[str] = None,
        limit: int = 20,
        verbose: bool = False,
    ):
        """Analyze usage patterns in reference data."""
        try:
            ref_path = Path(file_path)
            self.validate_file_exists(ref_path, "reference file")

            if verbose:
                self.console.print(f"[blue]Analyzing reference file: {ref_path}[/blue]")

            # Load the CSV file
            try:
                df = pl.read_csv(ref_path)
            except Exception as e:
                raise ValueError(f"Failed to read CSV file: {str(e)}")

            # Apply filters
            filtered_df = df
            if provider:
                filtered_df = filtered_df.filter(pl.col("cloud_provider") == provider)
            if service:
                filtered_df = filtered_df.filter(pl.col("service") == service)

            # Display overall statistics
            self._display_overall_stats(filtered_df, provider, service)

            # Display top usage patterns
            self._display_usage_patterns(filtered_df, limit)

        except Exception as e:
            self.handle_exception(e, "reference usage analysis", verbose)

    def list_providers(self, file_path: str):
        """List all cloud providers in reference data."""
        try:
            ref_path = Path(file_path)
            self.validate_file_exists(ref_path, "reference file")

            df = pl.read_csv(ref_path)

            if "cloud_provider" not in df.columns:
                self.console.print(
                    "[red]No 'cloud_provider' column found in reference file[/red]"
                )
                return

            # Get provider statistics
            provider_stats = (
                df.group_by("cloud_provider")
                .agg(pl.len().alias("count"))
                .sort("count", descending=True)
            ).to_dicts()

            display_summary_table(
                self.console,
                "Cloud Providers",
                provider_stats,
                ["cloud_provider", "count"],
            )

        except Exception as e:
            self.handle_exception(e, "provider listing")

    def list_services(self, file_path: str, provider: Optional[str] = None):
        """List all services in reference data."""
        try:
            ref_path = Path(file_path)
            self.validate_file_exists(ref_path, "reference file")

            df = pl.read_csv(ref_path)

            if "service" not in df.columns:
                self.console.print(
                    "[red]No 'service' column found in reference file[/red]"
                )
                return

            # Filter by provider if specified
            if provider:
                df = df.filter(pl.col("cloud_provider") == provider)
                title = f"Services for {provider}"
            else:
                title = "All Services"

            # Get service statistics
            service_stats = (
                df.group_by("service")
                .agg(pl.len().alias("count"))
                .sort("count", descending=True)
                .limit(50)  # Limit to top 50 services
            ).to_dicts()

            display_summary_table(
                self.console, title, service_stats, ["service", "count"]
            )

        except Exception as e:
            self.handle_exception(e, "service listing")

    def _display_overall_stats(
        self, df: pl.DataFrame, provider: Optional[str], service: Optional[str]
    ):
        """Display overall statistics."""
        stats = {
            "Total rows": len(df),
            "Unique providers": df.select("cloud_provider").n_unique()
            if "cloud_provider" in df.columns
            else 0,
            "Unique services": df.select("service").n_unique()
            if "service" in df.columns
            else 0,
            "Unique resource types": df.select("resource_type").n_unique()
            if "resource_type" in df.columns
            else 0,
        }

        filters_applied = []
        if provider:
            filters_applied.append(f"Provider: {provider}")
        if service:
            filters_applied.append(f"Service: {service}")

        title = "Reference Data Statistics"
        if filters_applied:
            title += f" ({', '.join(filters_applied)})"

        stats_data = [{"metric": k, "value": v} for k, v in stats.items()]

        display_summary_table(self.console, title, stats_data, ["metric", "value"])

    def _display_usage_patterns(self, df: pl.DataFrame, limit: int):
        """Display top usage patterns."""
        # Top resource types
        if "resource_type" in df.columns:
            resource_types = (
                df.group_by("resource_type")
                .agg(pl.len().alias("count"))
                .sort("count", descending=True)
                .limit(limit)
            ).to_dicts()

            display_summary_table(
                self.console,
                f"Top {limit} Resource Types",
                resource_types,
                ["resource_type", "count"],
            )

        # Top operations
        if "operation" in df.columns:
            operations = (
                df.group_by("operation")
                .agg(pl.len().alias("count"))
                .sort("count", descending=True)
                .limit(limit)
            ).to_dicts()

            display_summary_table(
                self.console,
                f"Top {limit} Operations",
                operations,
                ["operation", "count"],
            )


# Create Typer app
app = typer.Typer(help="Reference data usage analysis commands")
usage_cmd = ReferenceUsageCommand()


@app.command()
def analyze(
    file_path: str = typer.Argument(..., help="Path to reference CSV file"),
    provider: Optional[str] = typer.Option(
        None, "--provider", "-p", help="Filter by cloud provider"
    ),
    service: Optional[str] = typer.Option(
        None, "--service", "-s", help="Filter by service"
    ),
    limit: int = typer.Option(20, "--limit", "-l", help="Limit for top results"),
    verbose: bool = typer.Option(
        False, "--verbose", "-v", help="Enable verbose output"
    ),
):
    """Analyze usage patterns in reference data."""
    usage_cmd.analyze_usage(file_path, provider, service, limit, verbose)


@app.command()
def providers(file_path: str = typer.Argument(..., help="Path to reference CSV file")):
    """List all cloud providers in reference data."""
    usage_cmd.list_providers(file_path)


@app.command()
def services(
    file_path: str = typer.Argument(..., help="Path to reference CSV file"),
    provider: Optional[str] = typer.Option(
        None, "--provider", "-p", help="Filter by cloud provider"
    ),
):
    """List all services in reference data."""
    usage_cmd.list_services(file_path, provider)
