from typing import Optional
"""Allocation telemetry CLI commands."""

import typer

from ...telemetry.allocation import AllocationGenerator, AllocationsConfig
from ...utils.org_utils import load_telemetry_configs
from ..common import BaseCommand, display_summary_table


class AllocationCommand(BaseCommand):
    """Allocation telemetry generation command."""

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

            # Load telemetry configuration
            try:
                config_data = load_telemetry_configs(
                    org_dir, config_file or "allocations"
                )
                config_source = f"telemetry/configs/{config_file or 'allocations'}.yaml"
                if verbose:
                    self.console.print(
                        f"[blue]Loading configuration from: {config_source}[/blue]"
                    )
            except FileNotFoundError as e:
                self.console.print(f"[red]Telemetry config not found: {e}[/red]")
                self.console.print(
                    "[yellow]Expected location: telemetry/configs/allocations.yaml[/yellow]"
                )
                raise

            # Create config object from loaded data
            config = AllocationsConfig.from_dict(config_data)
            config.validate()

            # Determine output directory (use telemetry run type)
            output_path = self.determine_output_directory(
                org_dir, output_dir, "allocation", "telemetry"
            )

            # Generate allocation data
            self.console.print("[green]Generating allocation telemetry...[/green]")

            with self.create_progress_context() as progress:
                task = progress.add_task("Generating allocation data...", total=None)

                # Generate allocation data
                generator = AllocationGenerator(config)
                created_files = generator.generate_monthly_files(output_path)

                if verbose:
                    self.console.print(
                        f"[blue]Generated {len(created_files)} files[/blue]"
                    )

                progress.remove_task(task)

            # Display summary
            self._display_generation_summary(created_files, output_path)

        except Exception as e:
            self.handle_exception(e, "allocation telemetry generation", verbose)

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

            # Load telemetry configuration
            try:
                config_data = load_telemetry_configs(
                    org_dir, config_file or "allocations"
                )
                config_source = f"telemetry/configs/{config_file or 'allocations'}.yaml"
            except FileNotFoundError as e:
                self.console.print(f"[red]Telemetry config not found: {e}[/red]")
                raise

            # Load and validate configuration
            self.console.print(
                f"[blue]Validating configuration: {config_source}[/blue]"
            )
            config = AllocationsConfig.from_dict(config_data)
            config.validate()

            self.display_success(
                "Configuration is valid!",
                {
                    "Config source": config_source,
                    "Allocations defined": len(config.allocations)
                    if hasattr(config, "allocations")
                    else 0,
                },
            )

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

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

        if created_files:
            # Display file summary
            data = []
            for file_path in created_files:
                data.append(
                    {
                        "name": file_path.name,
                        "path": str(file_path.relative_to(output_path)),
                    }
                )

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


# Create Typer app
app = typer.Typer(help="Allocation telemetry generation commands")
allocation_cmd = AllocationCommand()


@app.command()
def generate(
    org: str = typer.Argument(..., help="Organization name"),
    config_file: Optional[str] = typer.Option(
        None, "--config", "-c", help="Custom allocation 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 allocation telemetry data for an organization."""
    allocation_cmd.generate_allocation(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 allocation config file path"
    ),
):
    """Validate allocation configuration file."""
    allocation_cmd.validate_config(org, config_file)
