"""Example command - Show example configurations."""

from typing import Optional

import click
import yaml

from .base import BaseCommand, console


class ExampleCommand(BaseCommand):
    """Show example configurations or save to file."""

    @property
    def name(self) -> str:
        return "example"

    @property
    def help(self) -> str:
        return "Show example configurations"

    def get_command(self) -> click.Command:
        @click.command(name=self.name, help=self.help)
        @click.argument("example_name", required=False)
        def example(example_name: Optional[str] = None):
            """Show example configurations or save to file."""
            self._execute(example_name)

        return example

    def _execute(self, example_name: Optional[str]) -> None:
        """Execute the example command."""
        examples = {
            "minimal": {
                "name": "minimal-example",
                "instance_type": "a100-80gb.sxm.1x",
                "command": 'echo "Hello from Flow SDK!" && hostname && date',
            },
            "gpu-test": {
                "name": "gpu-test",
                "instance_type": "a100-80gb.sxm.1x",
                "command": 'nvidia-smi && echo "GPU test completed!"',
                "max_price_per_hour": 5.0,
            },
            "system-info": {
                "name": "system-info",
                "instance_type": "a100-80gb.sxm.1x",
                "command": "bash -c \"echo === System Information ===; echo CPU: $(nproc) cores; echo Memory: $(free -h | grep Mem | awk '{print $2}'); echo Disk: $(df -h / | tail -1 | awk '{print $2}'); echo Kernel: $(uname -r); echo GPU: $(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null || echo No GPU detected)\"",
            },
            "training": {
                "name": "basic-training",
                "instance_type": "a100-80gb.sxm.2x",
                "region": "us-central1-a",
                "max_price_per_hour": 10.0,
                "volumes": [
                    {"size_gb": 100, "mount_path": "/data"},
                    {"size_gb": 50, "mount_path": "/checkpoints"},
                ],
                "environment": {"CUDA_VISIBLE_DEVICES": "0,1", "TF_CPP_MIN_LOG_LEVEL": "2"},
                "command": '''#!/bin/bash
echo "Starting training job..."

# Simulated training loop
for epoch in {1..5}; do
    echo "[$(date)] Epoch $epoch/5"
    sleep 2
done

echo "Training completed!"
echo "Final metrics: accuracy=0.94, loss=0.123"''',
            },
        }

        if example_name is None:
            # List all examples
            console.print("Available examples:")
            for name, config in examples.items():
                console.print(f"  [cyan]{name}[/cyan] - {config.get('name', 'No description')}")
            console.print("\nUsage: flow example <name>")
            console.print("Redirect output to save: [dim]flow example minimal > job.yaml[/dim]")
        elif example_name in examples:
            # Show specific example
            yaml_content = yaml.dump(examples[example_name], default_flow_style=False, sort_keys=False)
            console.print(yaml_content)
        else:
            console.print(f"[red]Error:[/red] Unknown example: {example_name}")
            console.print(f"Available: {', '.join(examples.keys())}")
            raise click.exceptions.Exit(1)


# Export command instance
command = ExampleCommand()
