"""Info and version commands - System information."""

from __future__ import annotations

import sys

import click

from ..utils.config import DEFAULT_CONFIG
from ..utils.console import get_console


@click.command()
def info() -> None:
    """Show system information and device detection.

    Displays:
      - Python version
      - sageLLM version
      - CUDA availability
      - Ascend NPU availability
      - Config file location
    """
    console = get_console()
    from rich.panel import Panel
    from rich.table import Table

    console.print()
    console.print(
        Panel.fit("[bold blue]sageLLM System Information[/bold blue]", border_style="blue")
    )
    console.print()

    table = Table(show_header=True, header_style="bold magenta")
    table.add_column("Component", style="cyan", width=20)
    table.add_column("Status", width=50)

    # Helper function to get package version using importlib.metadata
    # This is more reliable than importing the module, especially for
    # compiled packages
    def get_pkg_version(pkg_name: str) -> str | None:
        """Get package version without importing the module."""
        from importlib.metadata import PackageNotFoundError, version

        try:
            return version(pkg_name)
        except PackageNotFoundError:
            return None

    # Python version
    table.add_row("Python", f"{sys.version.split()[0]}")

    # sageLLM version
    ver = get_pkg_version("isagellm")
    if ver:
        table.add_row("sageLLM", f"✅ {ver}")
    else:
        table.add_row("sageLLM", "❌ Not installed")

    # Sub-packages (required)
    ver = get_pkg_version("isagellm-protocol")
    if ver:
        table.add_row("  └─ protocol", f"✅ {ver}")
    else:
        table.add_row("  └─ protocol", "❌ Not installed")

    ver = get_pkg_version("isagellm-core")
    if ver:
        table.add_row("  └─ core", f"✅ {ver}")
    else:
        table.add_row("  └─ core", "❌ Not installed")

    ver = get_pkg_version("isagellm-backend")
    if ver:
        table.add_row("  └─ backend", f"✅ {ver}")
    else:
        table.add_row("  └─ backend", "❌ Not installed")

    # Optional packages
    ver = get_pkg_version("isagellm-control-plane")
    if ver:
        table.add_row("  └─ control-plane", f"✅ {ver}")
    else:
        table.add_row("  └─ control-plane", "[dim]○ Not installed[/dim]")

    ver = get_pkg_version("isagellm-gateway")
    if ver:
        table.add_row("  └─ gateway", f"✅ {ver}")
    else:
        table.add_row("  └─ gateway", "[dim]○ Not installed[/dim]")

    # CUDA detection
    cuda_status = detect_cuda()
    table.add_row("CUDA", cuda_status)

    # Ascend detection
    ascend_status = detect_ascend()
    table.add_row("Ascend (昇腾)", ascend_status)

    # Config location
    config_exists = "✅" if DEFAULT_CONFIG.exists() else "❌"
    table.add_row("Config", f"{config_exists} {DEFAULT_CONFIG}")

    console.print(table)
    console.print()

    # Quick start hints
    console.print("[dim]Quick start:[/dim]")
    console.print("  [cyan]sagellm install cuda[/cyan]   Install CUDA support")
    console.print("  [cyan]sagellm serve[/cyan]          Start local engine")
    console.print("  [cyan]sagellm run -p 'Hi'[/cyan]    Run inference")
    console.print("  [cyan]sagellm demo[/cyan]           Run demo validation")
    console.print("  [cyan]sagellm gateway[/cyan]        Start API gateway")
    console.print()


@click.command()
@click.option(
    "--format", "fmt", type=click.Choice(["json", "yaml"]), default="yaml", help="Output format"
)
def version(fmt: str) -> None:
    """Show version information."""
    from importlib.metadata import PackageNotFoundError
    from importlib.metadata import version as get_version

    console = get_console()

    def get_pkg_ver(pkg_name: str) -> str:
        try:
            return get_version(pkg_name)
        except PackageNotFoundError:
            return "not installed"

    versions = {
        "sagellm": get_pkg_ver("isagellm"),
        "protocol": get_pkg_ver("isagellm-protocol"),
        "core": get_pkg_ver("isagellm-core"),
        "backend": get_pkg_ver("isagellm-backend"),
        "control-plane": get_pkg_ver("isagellm-control-plane"),
        "gateway": get_pkg_ver("isagellm-gateway"),
    }

    if fmt == "json":
        import json

        console.print(json.dumps(versions, indent=2))
    else:
        for pkg, ver in versions.items():
            console.print(f"{pkg}: {ver}")


def detect_cuda() -> str:
    """Detect CUDA availability."""
    try:
        import torch

        if torch.cuda.is_available():
            device_count = torch.cuda.device_count()
            device_name = torch.cuda.get_device_name(0)
            return f"✅ {device_count} device(s) - {device_name}"
        else:
            return "❌ torch installed, no GPU"
    except ImportError:
        return "❌ torch not installed"
    except Exception as e:
        return f"❌ Error: {e}"


def detect_ascend() -> str:
    """Detect Ascend NPU availability."""
    try:
        import torch_npu

        if torch_npu.npu.is_available():
            device_count = torch_npu.npu.device_count()
            return f"✅ {device_count} NPU(s)"
        else:
            return "❌ torch_npu installed, no NPU"
    except ImportError:
        return "❌ torch_npu not installed"
    except Exception as e:
        return f"❌ Error: {e}"
