"""CLI commands for usage allocation."""

from typing import List, Optional

import typer
from rich.console import Console

from ..config.models import load_usage_config
from ..core.processor import process_usage_allocation

console = Console()
usage_app = typer.Typer(
    name="usage",
    help="Usage allocation commands for transforming cost data into usage metrics",
    no_args_is_help=True
)


@usage_app.command("run")
def run_usage_allocation(
    config: str = typer.Option(..., help="Path to usage configuration YAML file"),
    month: Optional[str] = typer.Option(None, help="Specific month (YYYY-MM) - optional override"),
    force: bool = typer.Option(False, "--force", help="Force reprocessing of completed months"),
):
    """
    Process usage allocation for billing data.
    
    Reads from metadata stage S3 output and writes to usage stage S3 output.
    Processes one month at a time with fail-fast behavior.
    Skips already processed months unless --force is used.
    Uses progressive fallback matching against unified reference data.
    """
    try:
        # FAIL FAST: Validate AWS credentials before any work
        from ...services.environment_service import EnvironmentService
        env_service = EnvironmentService()
        env_service.validate_aws_credentials_and_access()
        
        # Load and validate configuration
        usage_config = load_usage_config(config)
        console.print(f"🔧 Loaded configuration for dataset: {usage_config.dataset_name}")
        
        # Process usage allocation
        result = process_usage_allocation(
            config=usage_config,
            specific_month=month,
            force=force
        )
        
        if result.success:
            console.print("🎉 Usage allocation completed successfully")
        else:
            console.print(f"❌ Usage allocation failed: {result.error}")
            raise typer.Exit(1)
            
    except ValueError as e:
        # This catches both AWS credential errors and configuration errors
        console.print(f"❌ {str(e)}")
        raise typer.Exit(1)
    except FileNotFoundError as e:
        console.print(f"❌ Configuration file error: {e}")
        raise typer.Exit(1)
    except Exception as e:
        console.print(f"❌ Unexpected error: {e}")
        raise typer.Exit(1)


@usage_app.command("validate")
def validate_usage_quality(
    config: str = typer.Option(..., help="Path to usage configuration YAML file"),
    months: Optional[List[str]] = typer.Option(None, help="Months to validate (YYYY-MM)"),
):
    """Validate usage allocation quality and coverage."""
    try:
        # FAIL FAST: Validate AWS credentials before any work
        from ...services.environment_service import EnvironmentService
        env_service = EnvironmentService()
        env_service.validate_aws_credentials_and_access()
        
        usage_config = load_usage_config(config)
        console.print(f"🔧 Validating usage quality for dataset: {usage_config.dataset_name}")
        
        # TODO: Implement validation logic
        console.print("⚠️  Validation not yet implemented")
        
    except ValueError as e:
        # This catches both AWS credential errors and configuration errors
        console.print(f"❌ {str(e)}")
        raise typer.Exit(1)
    except Exception as e:
        console.print(f"❌ Validation error: {e}")
        raise typer.Exit(1)


@usage_app.command("status")
def show_usage_status(
    config: str = typer.Option(..., help="Path to usage configuration YAML file"),
):
    """Show status of usage allocation processing."""
    try:
        # FAIL FAST: Validate AWS credentials before any work
        from ...services.environment_service import EnvironmentService
        env_service = EnvironmentService()
        env_service.validate_aws_credentials_and_access()
        
        usage_config = load_usage_config(config)
        console.print(f"🔧 Checking status for dataset: {usage_config.dataset_name}")
        
        # TODO: Implement status checking logic
        console.print("⚠️  Status checking not yet implemented")
        
    except ValueError as e:
        # This catches both AWS credential errors and configuration errors
        console.print(f"❌ {str(e)}")
        raise typer.Exit(1)
    except Exception as e:
        console.print(f"❌ Status check error: {e}")
        raise typer.Exit(1)