"""Display utilities for CLI."""

from .console import get_console

# Version from package
try:
    from sagellm import __version__
except ImportError:
    __version__ = "0.1.0"


def _detected_hardware_summary() -> tuple[str, list[str]]:
    """Quick hardware detection for the welcome banner.

    Returns:
        (status_line, list_of_available_backends)
    """
    available: list[str] = []
    parts: list[str] = []

    # Check Ascend NPU
    try:
        import torch_npu  # type: ignore[import-untyped]

        if torch_npu.npu.is_available():
            count = torch_npu.npu.device_count()
            parts.append(f"[green]Ascend: {count} NPU(s) \u2713[/green]")
            available.append("ascend")
    except Exception:
        pass

    # Check CUDA
    if "ascend" not in available:
        try:
            import torch

            if torch.cuda.is_available():
                gpu = torch.cuda.get_device_name(0)
                vram = round(torch.cuda.get_device_properties(0).total_memory / (1024**3), 1)
                parts.append(f"[green]CUDA: {gpu} ({vram} GB) \u2713[/green]")
                available.append("cuda")
        except Exception:
            pass

    if not available:
        try:
            import torch  # noqa: F401

            parts.append("[yellow]GPU: none detected \u2014 CPU only[/yellow]")
        except ImportError:
            parts.append("[yellow]PyTorch: not installed[/yellow]")
        available.append("cpu")

    status = "  \u2502  ".join(parts) if parts else "[dim]CPU only[/dim]"
    return status, available


def show_welcome_message(cli_name: str = "sagellm") -> None:
    """Show welcome message with supported backends when running CLI without subcommand."""
    console = get_console()

    console.print()
    console.print(f"[bold blue]\ud83d\ude80 sageLLM v{__version__}[/bold blue]")
    console.print("[dim]Modular LLM inference engine for domestic computing power[/dim]")
    console.print()

    # Live hardware detection summary
    hw_status, available_backends = _detected_hardware_summary()
    console.print(f"[bold]Hardware detected:[/bold]  {hw_status}")
    console.print()

    # Show supported backends with live status markers
    console.print("[bold]Supported backends (按优先级排序):[/bold]")
    console.print()

    def _marker(backend: str) -> str:
        return "[green]\u2713[/green]" if backend in available_backends else "[dim]\u25cb[/dim]"

    console.print("  [cyan]国产芯片 (Domestic):[/cyan]")
    console.print(
        f"    {_marker('ascend')} [green]ascend[/green]"
        "     华为昇腾 Ascend NPU    [dim](priority: 100)[/dim]"
    )
    console.print(
        f"    {_marker('kunlun')} [green]kunlun[/green]"
        "     百度昆仑 Kunlun XPU    [dim](priority: 90)[/dim]"
    )
    console.print(
        f"    {_marker('haiguang')} [green]haiguang[/green]"
        "   海光 DCU               [dim](priority: 85)[/dim]"
    )
    console.print(
        f"    {_marker('muxi')} [green]muxi[/green]"
        "       沐曦 Muxi GPU          [dim](priority: 80)[/dim]"
    )
    console.print()
    console.print("  [cyan]NVIDIA:[/cyan]")
    console.print(
        f"    {_marker('cuda')} [green]cuda[/green]"
        "       NVIDIA CUDA 12.1       [dim](priority: 50)[/dim]"
    )
    console.print(
        "    [dim]\u25cb[/dim] [green]cuda11[/green]"
        "     NVIDIA CUDA 11.8       [dim](for older drivers)[/dim]"
    )
    console.print()
    console.print("  [cyan]CPU:[/cyan]")
    console.print(
        "    [green]\u2713[/green] [green]cpu[/green]"
        "        CPU only               [dim](priority: 10, fallback)[/dim]"
    )
    console.print()

    # Show contextual quick start based on detected hardware
    console.print("[bold]Quick start:[/bold]")
    console.print()
    if "ascend" in available_backends or "cuda" in available_backends:
        console.print(
            f"  [bold cyan]{cli_name} hello[/bold cyan]            # \ud83d\ude80 一键验证推理（推荐首先运行）"
        )
    else:
        console.print(
            f"  [bold cyan]{cli_name} hello --cpu[/bold cyan]       # \ud83d\ude80 一键验证推理（CPU 模式）"
        )
        console.print(f"  [cyan]{cli_name} install cuda[/cyan]     # 安装 NVIDIA CUDA 支持")
        console.print(f"  [cyan]{cli_name} install ascend[/cyan]   # 安装华为昇腾支持")
    console.print(f"  [cyan]{cli_name} run -p 'Hello!'[/cyan]  # 运行推理")
    console.print(f"  [cyan]{cli_name} serve[/cyan]            # 启动 OpenAI 兼容 API 服务")
    console.print(f"  [cyan]{cli_name} info[/cyan]             # 查看完整系统信息")
    console.print(f"  [cyan]{cli_name} setup[/cyan]            # 交互式模型推荐向导")
    console.print()

    console.print(f"[dim]Run '{cli_name} --help' for all commands.[/dim]")
    console.print()
