"""CLI commands for discount allocation."""

from typing import List, Optional

import typer
from rich.console import Console

from ..config.models import load_discount_config
from ..core.processor import process_discount_allocation

console = Console()
discount_app = typer.Typer(
    name="discount",
    help="Discount allocation commands for applying cloud billing discounts",
    no_args_is_help=True
)


@discount_app.command("run")
def run_discount_allocation(
    config: str = typer.Option(..., help="Path to discount 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"),
    api: bool = typer.Option(False, "--api", help="Execute via API - same as default (kept for backward compatibility)"),
    local: bool = typer.Option(False, "--local", help="Execute locally instead of via API (for development/debugging)"),
):
    """
    Apply discount allocation to billing data.

    Processes from usage stage first, then fills gaps from metadata stage.
    Uses selective processor activation (currently Spot instances only).
    Applies realistic discount percentages with resource tracking.

    IMPORTANT: Validates AWS credentials before processing (fail-fast).

    Execution modes:
    - Default: Submit to Lambda API for processing on ECS workers (scalable, observable)
    - --local: Execute locally for development, debugging, or small datasets
    - --api: Explicit API execution (same as default, kept for backward compatibility)
    """
    # Validate mutually exclusive flags
    if api and local:
        console.print("[red]❌ Cannot specify both --api and --local[/red]")
        raise typer.Exit(1)

    # Execute locally if --local flag provided
    if local:
        console.print("[dim]⚙️  Executing locally...[/dim]")
        _execute_discount_locally(config, month, force)
        return

    # Default: Execute via API
    console.print("[cyan]☁️  Executing via API (Lambda + ECS workers)...[/cyan]")
    from pathlib import Path
    from src.api.cli_helper import execute_stage_via_api

    execute_stage_via_api(
        job_type="discount",
        config_path=Path(config),
        month=month,
        force=force,
    )


def _execute_discount_locally(
    config: str,
    month: Optional[str],
    force: bool
):
    """Execute discount allocation locally."""

    try:
        # FAIL FAST: Validate AWS credentials before any work
        from src.services.environment_service import EnvironmentService
        env_service = EnvironmentService()
        env_service.validate_aws_credentials_and_access()
        
        # Load and validate configuration
        discount_config = load_discount_config(config)
        console.print(f"🔧 Loaded configuration for dataset: {discount_config.dataset_name}")
        
        # Process discount allocation
        result = process_discount_allocation(
            config=discount_config,
            specific_month=month,
            force=force
        )
        
        if result.success:
            console.print(f"✅ [bold green]Discount allocation completed successfully[/bold green]")
            console.print(f"📊 Processed {result.processed_months} months")
            if hasattr(result, 'usage_months') and hasattr(result, 'metadata_gaps'):
                console.print(f"   - Usage stage: {result.usage_months} months")
                console.print(f"   - Metadata gaps: {result.metadata_gaps} months")
        else:
            console.print(f"❌ [bold red]Discount allocation failed[/bold red]")
            console.print(f"💥 Error: {result.error}")
            raise typer.Exit(1)
            
    except FileNotFoundError as e:
        console.print(f"❌ [bold red]Configuration file not found[/bold red]: {e}")
        raise typer.Exit(1)
    except ValueError as e:
        console.print(f"❌ [bold red]Configuration error[/bold red]: {e}")
        raise typer.Exit(1)
    except Exception as e:
        console.print(f"❌ [bold red]Unexpected error[/bold red]: {e}")
        raise typer.Exit(1)


@discount_app.command("status")
def show_discount_status(
    config: str = typer.Option(..., help="Path to discount configuration YAML file"),
):
    """Show status of discount allocation processing."""
    try:
        # Load configuration
        discount_config = load_discount_config(config)
        console.print(f"📊 [bold]Discount Status for {discount_config.dataset_name}[/bold]")
        
        # TODO: Implement status checking logic
        console.print("⚠️  Status checking not yet implemented")
        
    except Exception as e:
        console.print(f"❌ [bold red]Error checking status[/bold red]: {e}")
        raise typer.Exit(1)