"""hello command - one-click inference test."""

import sys

import click


@click.command()
@click.option("--cpu", is_flag=True, help="Force CPU backend (skip CUDA detection)")
def hello(cpu: bool) -> None:
    """🚀 One-click inference test - verify installation works!

    Downloads a small model and runs a simple inference.
    Auto-detects CUDA GPU and uses it if available.

    \b
    Example:
      pip install isagellm
    sagellm hello            # Auto-detect (uses GPU if available)
    sagellm hello --cpu      # Force CPU
    """
    from ..utils.backend import detect_ascend
    from ..utils.console import get_console

    console = get_console()
    console.print("\n[bold blue]🚀 sageLLM Hello World[/bold blue]\n")

    # Detect backend
    backend_kind = "cpu"
    if not cpu:
        # Try CUDA first
        try:
            import torch

            if torch.cuda.is_available() and torch.cuda.device_count() > 0:
                torch.zeros(1).cuda()  # Test CUDA actually works
                backend_kind = "cuda"
                gpu_name = torch.cuda.get_device_name(0)
                console.print(f"[green]✅ CUDA detected:[/green] {gpu_name}")
        except Exception:
            pass

        # Try Ascend if CUDA not available
        if backend_kind == "cpu":
            if "✅" in detect_ascend():
                backend_kind = "ascend"
                console.print("[green]✅ Ascend NPU detected[/green]")

    if backend_kind == "cpu":
        console.print("[yellow]ℹ️  Using CPU backend[/yellow]")

    try:
        import asyncio

        # Use a small but capable model for quick test
        model_name = "Qwen/Qwen2.5-0.5B-Instruct"
        prompt = "Hello, sageLLM!"

        console.print(f"[cyan]📦 Model:[/cyan] {model_name}")
        console.print(f"[cyan]💬 Prompt:[/cyan] {prompt}")
        console.print(
            f"[cyan]🔧 Backend:[/cyan] {backend_kind.upper() if backend_kind != 'cpu' else 'CPU'}\n"
        )

        async def _hello() -> None:
            from sagellm_core.llm_engine import LLMEngine, LLMEngineConfig
            from sagellm_protocol.sampling import SamplingParams

            provider_name = backend_kind

            config = LLMEngineConfig(
                model_path=model_name,
                backend_type=provider_name,
                max_new_tokens=30,
            )
            engine = LLMEngine(config)

            console.print("[dim]Loading model (first run downloads ~1GB)...[/dim]")
            await engine.start()

            try:
                sampling_params = SamplingParams(
                    max_tokens=20,
                    temperature=0.7,
                )

                response = await engine.generate(prompt, sampling_params=sampling_params)

                console.print("\n[green]✅ Inference successful![/green]")
                console.print(f"[cyan]📝 Output:[/cyan] {response.output_text[:100]}")
                console.print("\n[blue]📊 Metrics:[/blue]")
                console.print(f"   TTFT: {response.metrics.ttft_ms:.1f} ms")
                console.print(f"   Throughput: {response.metrics.throughput_tps:.1f} tokens/s")
                console.print("\n[bold green]🎉 sageLLM is working! Try:[/bold green]")
                console.print("   [cyan]sagellm run -p 'Your prompt here'[/cyan]")
                console.print("   [cyan]sagellm serve[/cyan]  # Start API server")
                console.print()
            finally:
                await engine.stop()

        asyncio.run(_hello())

    except ImportError as e:
        console.print(f"[red]❌ Import error: {e}[/red]")
        console.print("\n[yellow]💡 Install the right PyTorch backend first:[/yellow]")
        console.print("   [cyan]sagellm install cuda[/cyan]    # NVIDIA GPU")
        console.print("   [cyan]sagellm install ascend[/cyan]  # Huawei Ascend NPU")
        console.print("   [cyan]sagellm install cpu[/cyan]     # CPU only (no GPU)")
        sys.exit(1)
    except Exception as e:
        console.print(f"[red]❌ Error: {e}[/red]")
        import traceback

        console.print(f"[dim]{traceback.format_exc()}[/dim]")
        sys.exit(1)
