"""
Show reference dataset status and summary information.
"""

import typer
from pathlib import Path
from typing import Optional
import polars as pl
from rich.console import Console
from rich.table import Table

from ..common import BaseCommand, display_summary_table
from .reference_loader import load_reference_data, ensure_reference_data_available
from ...services.environment_service import env_service

console = Console()
app = typer.Typer(help="Reference dataset status and statistics")


class DataStatusCommand(BaseCommand):
    """Show reference dataset status."""
    
    def show_status(
        self,
        verbose: bool = False
    ):
        """Show dataset health, growth, and summary statistics."""
        try:
            # Load reference data from S3 only
            df = load_reference_data()
            
            if df is None:
                if not ensure_reference_data_available():
                    return
            
            if verbose:
                console.print(f"[blue]Loaded reference data: {df.height:,} rows[/blue]")
            
            # Display overall status
            self._display_overall_status(df)
            
            # Display provider summary
            self._display_provider_summary(df)
            
            # Display coverage details
            self._display_coverage_details(df)
            
            # Display top combinations
            self._display_top_combinations(df)
            
        except Exception as e:
            self.handle_exception(e, "showing dataset status", verbose)
    
    def _display_overall_status(self, df: pl.DataFrame):
        """Display overall dataset status."""
        total_combinations = df.height
        with_pricing = df.filter(pl.col("has_pricing")).height
        coverage_pct = (with_pricing / total_combinations * 100) if total_combinations > 0 else 0
        
        console.print(f"📊 [bold]Reference Dataset Status[/bold]")
        console.print(f"========================")
        console.print(f"📊 Total combinations: {total_combinations:,}")
        console.print(f"💰 With pricing data: {with_pricing:,}")
        console.print(f"📈 Coverage: {coverage_pct:.1f}%")
        console.print(f"💾 Data source: S3 (cached locally)")
    
    def _display_provider_summary(self, df: pl.DataFrame):
        """Display summary by provider."""
        provider_summary = df.group_by("cloud_provider").agg([
            pl.len().alias("total_combinations"),
            pl.col("has_pricing").sum().alias("with_pricing"),
            pl.col("record_count").sum().alias("total_records")
        ]).sort("total_combinations", descending=True)
        
        # Add coverage percentage
        provider_summary = provider_summary.with_columns([
            (pl.col("with_pricing") / pl.col("total_combinations") * 100).round(1).alias("coverage_pct")
        ])
        
        console.print(f"\n🏢 [bold]Top Providers (showing up to 10):[/bold]")
        
        # Convert to list for display
        provider_data = []
        for row in provider_summary.head(10).iter_rows(named=True):
            provider_data.append({
                "provider": row["cloud_provider"],
                "combinations": f"{row['total_combinations']:,}",
                "with_pricing": f"{row['with_pricing']:,}",
                "coverage": f"{row['coverage_pct']:.1f}%",
                "records": f"{row['total_records']:,}"
            })
        
        display_summary_table(
            console,
            "Provider Summary",
            provider_data,
            ["provider", "combinations", "with_pricing", "coverage", "records"]
        )
    
    def _display_coverage_details(self, df: pl.DataFrame):
        """Display coverage analysis."""
        # Coverage by provider type
        major_providers = ["AWS", "GCP", "Azure"]
        major_coverage = df.filter(pl.col("cloud_provider").is_in(major_providers))
        other_coverage = df.filter(~pl.col("cloud_provider").is_in(major_providers))
        
        console.print(f"\n📈 [bold]Coverage Analysis:[/bold]")
        
        if not major_coverage.is_empty():
            major_total = major_coverage.height
            major_with_pricing = major_coverage.filter(pl.col("has_pricing")).height
            major_pct = (major_with_pricing / major_total * 100) if major_total > 0 else 0
            console.print(f"   Major providers (AWS/GCP/Azure): {major_with_pricing:,}/{major_total:,} ({major_pct:.1f}%)")
        
        if not other_coverage.is_empty():
            other_total = other_coverage.height
            other_with_pricing = other_coverage.filter(pl.col("has_pricing")).height
            other_pct = (other_with_pricing / other_total * 100) if other_total > 0 else 0
            console.print(f"   Other providers: {other_with_pricing:,}/{other_total:,} ({other_pct:.1f}%)")
        
        # Service usage vs specific types
        service_usage = df.filter(pl.col("resource_type") == "service-usage")
        specific_types = df.filter(pl.col("resource_type") != "service-usage")
        
        if not service_usage.is_empty():
            su_total = service_usage.height
            su_pct = (su_total / df.height * 100) if df.height > 0 else 0
            console.print(f"   Generic 'service-usage': {su_total:,} ({su_pct:.1f}%)")
        
        if not specific_types.is_empty():
            st_total = specific_types.height
            st_pct = (st_total / df.height * 100) if df.height > 0 else 0
            console.print(f"   Specific resource types: {st_total:,} ({st_pct:.1f}%)")
    
    def _display_top_combinations(self, df: pl.DataFrame):
        """Display top combinations with pricing."""
        # Top combinations by cost
        top_cost = df.filter(pl.col("has_pricing") & pl.col("total_cost").is_not_null()) \
                    .sort("total_cost", descending=True) \
                    .head(5)
        
        if not top_cost.is_empty():
            console.print(f"\n💰 [bold]Top 5 Combinations by Cost:[/bold]")
            for row in top_cost.iter_rows(named=True):
                cost = row["total_cost"]
                console.print(f"   ${cost:,.2f} - {row['cloud_provider']}/{row['service']}/{row['usage_family']}")
        
        # Most common combinations
        top_common = df.sort("record_count", descending=True).head(5)
        
        if not top_common.is_empty():
            console.print(f"\n📊 [bold]Most Common Combinations:[/bold]")
            for row in top_common.iter_rows(named=True):
                count = row["record_count"]
                pricing_indicator = " ✓" if row["has_pricing"] else ""
                console.print(f"   {count} records - {row['cloud_provider']}/{row['service']}/{row['usage_family']}{pricing_indicator}")


# Create command instance
status_cmd = DataStatusCommand()


@app.command()
def overview(
    verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable verbose output")
):
    """Show dataset health, growth, and summary statistics."""
    try:
        # FAIL FAST: Validate AWS credentials before any work
        env_service.validate_aws_credentials_and_access()
        
        status_cmd.show_status(verbose)
    except ValueError as e:
        console.print(f"❌ {str(e)}")
        raise typer.Exit(1)