"""bilge profile - Analyze hardware."""

import json
from pathlib import Path

import typer
from rich.console import Console
from rich.table import Table

from bilgeai.core.constants import PROJECT_DIR
from bilgeai.profiler import get_hardware_profile

console = Console()


def profile_command(
    save: bool = typer.Option(True, help="Save profile to .bilge/ directory"),
) -> None:
    """Analyze hardware (CPU, RAM, GPU, CUDA)."""
    console.print("[bold]Profiling hardware...[/bold]\n")

    hw = get_hardware_profile()

    table = Table(title="Hardware Profile", show_header=True)
    table.add_column("Component", style="cyan")
    table.add_column("Details", style="green")

    table.add_row("CPU", f"{hw.cpu_name} ({hw.cpu_cores} cores)")
    table.add_row("RAM", f"{hw.ram_total_gb:.1f} GB ({hw.ram_available_gb:.1f} GB available)")
    table.add_row("Disk", f"{hw.disk_free_gb:.1f} GB free")
    table.add_row("OS", hw.os)
    table.add_row("Python", hw.python_version)

    if hw.torch_version:
        table.add_row("PyTorch", hw.torch_version)

    table.add_row("CUDA Available", "Yes" if hw.cuda_available else "No")

    if hw.gpus:
        for i, gpu in enumerate(hw.gpus):
            prefix = f"GPU {i}" if hw.num_gpus > 1 else "GPU"
            vendor_tag = f" [{gpu.vendor.upper()}]" if gpu.vendor != "nvidia" else ""
            table.add_row(prefix, f"{gpu.name} ({gpu.vram_gb:.1f} GB){vendor_tag}")
            if gpu.cuda_version:
                table.add_row("  CUDA", gpu.cuda_version)
            if gpu.compute_capability:
                table.add_row("  Compute Cap.", gpu.compute_capability)
        if hw.num_gpus > 1:
            table.add_row(
                "[bold]GPU Total[/bold]",
                f"[bold]{hw.num_gpus} GPUs, {hw.total_vram_gb:.1f} GB total VRAM[/bold]",
            )
    else:
        table.add_row("GPU", "[yellow]No GPU detected[/yellow]")

    console.print(table)

    # Save profile to .bilge/
    if save:
        project_dir = Path.cwd() / PROJECT_DIR
        project_dir.mkdir(parents=True, exist_ok=True)
        profile_path = project_dir / "hardware_profile.json"
        profile_path.write_text(
            json.dumps(hw.model_dump(), indent=2, ensure_ascii=False), encoding="utf-8"
        )
        console.print(f"\n[dim]Profile saved to {profile_path}[/dim]")

    from bilgeai.cli.hints import show_next_hint

    show_next_hint("profile", console)
