"""CLI commands for telemetry generation."""

from datetime import datetime
from pathlib import Path

import typer
import yaml

from ..telemetry import TelemetryConfig, TelemetryGenerator

app = typer.Typer(help="Generate demo telemetry data for CloudZero UCA")


@app.command("generate")
def generate_telemetry(
    config: Path = typer.Option(
        ..., "--config", "-c", help="Path to telemetry config YAML"
    ),
    output_dir: Path = typer.Option(
        None, "--output", "-o", help="Output directory (default: outputs/telemetry/)"
    ),
):
    """Generate telemetry CSV from config file.

    Creates timestamped output directory with:
    - telemetry.csv: 3-column CSV (timestamp, element_id, unit_value)
    - config.yaml: Copy of input config for reproducibility
    """
    try:
        # Load and validate config
        telemetry_config = TelemetryConfig.from_yaml(config)
        typer.echo(f"✓ Loaded config: {config}")
        typer.echo(f"  Date range: {telemetry_config.start_date} to {telemetry_config.end_date}")
        typer.echo(f"  Elements: {len(telemetry_config.elements)}")

        # Count anomalies
        anomaly_count = sum(
            1 for a in telemetry_config.elements.values() if a is not None
        )
        typer.echo(f"  Anomalies: {anomaly_count}")

        # Create timestamped output directory
        output_path = create_output_directory(output_dir)
        typer.echo(f"\n✓ Output directory: {output_path}")

        # Generate telemetry data
        typer.echo("\nGenerating telemetry data...")
        generator = TelemetryGenerator(telemetry_config)
        df = generator.generate()

        # Write CSV
        csv_path = output_path / "telemetry.csv"
        df.write_csv(csv_path)
        typer.echo(f"✓ Wrote {len(df)} records to telemetry.csv")

        # Copy config for reproducibility
        config_copy_path = output_path / "config.yaml"
        with open(config_copy_path, "w") as f:
            yaml.dump(telemetry_config.to_yaml_dict(), f, default_flow_style=False)
        typer.echo(f"✓ Copied config to config.yaml")

        # Summary
        typer.echo(f"\n✅ Telemetry generation complete!")
        typer.echo(f"   {len(df)} records")
        typer.echo(f"   {len(telemetry_config.elements)} elements")
        typer.echo(f"   {output_path}")

    except Exception as e:
        typer.echo(f"\n❌ Error: {e}", err=True)
        raise typer.Exit(code=1)


@app.command("validate")
def validate_config(
    config: Path = typer.Argument(..., help="Path to telemetry config YAML")
):
    """Validate telemetry configuration file."""
    try:
        telemetry_config = TelemetryConfig.from_yaml(config)

        typer.echo(f"✅ Configuration is valid!")
        typer.echo(f"   Config: {config}")
        typer.echo(f"   Date range: {telemetry_config.start_date} to {telemetry_config.end_date}")
        typer.echo(f"   Elements: {len(telemetry_config.elements)}")

        # Count anomalies by type
        anomaly_types = {}
        for anomaly_type in telemetry_config.elements.values():
            if anomaly_type is not None:
                anomaly_types[anomaly_type] = anomaly_types.get(anomaly_type, 0) + 1

        if anomaly_types:
            typer.echo("   Anomalies:")
            for anom_type, count in anomaly_types.items():
                typer.echo(f"     - {anom_type}: {count}")

    except Exception as e:
        typer.echo(f"\n❌ Validation failed: {e}", err=True)
        raise typer.Exit(code=1)


def create_output_directory(base_dir: Path = None) -> Path:
    """Create timestamped output directory."""
    if base_dir is None:
        base_dir = Path("outputs/telemetry")

    # Create timestamped subdirectory
    timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    output_path = base_dir / timestamp

    output_path.mkdir(parents=True, exist_ok=True)
    return output_path
