"""CLI main entry point."""

import os
import sys
import warnings
from pathlib import Path

# =============================================================================
# Global warning suppression for torch_npu
# =============================================================================
# Suppress torch_npu's "owner does not match" warnings at the earliest point.
# This happens when CANN toolkit is installed by root but used by non-root user.
# Must be set BEFORE any torch_npu import anywhere in the codebase.
warnings.filterwarnings(
    "ignore",
    message=".*owner does not match.*",
    category=UserWarning,
    module="torch_npu.*",
)

import click

# =============================================================================
# Initialize software environment at the very start
# =============================================================================
from .utils.env_detector import EnvInitializer

# Initialize all software-level environment variables
# This happens BEFORE any command execution
EnvInitializer.init_all(verbose=False)

from .utils.display import show_welcome_message

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


CANONICAL_CLI_NAME = "sagellm"
SETUP_HINT_MARKER = Path.home() / ".sagellm" / ".setup_hint_shown"


def _maybe_show_setup_hint(invoked_subcommand: str | None) -> None:
    """Show one-time onboarding hint for interactive users."""
    if invoked_subcommand == "setup":
        return
    if os.getenv("SAGELLM_DISABLE_SETUP_HINT", "0").strip() == "1":
        return
    if not sys.stdout.isatty():
        return
    if SETUP_HINT_MARKER.exists():
        return

    SETUP_HINT_MARKER.parent.mkdir(parents=True, exist_ok=True)
    click.secho(
        "💡 首次使用建议先运行: sagellm setup  (或 sagellm-setup)",
        fg="yellow",
        err=True,
    )
    click.secho("   该向导会检测硬件并推荐可运行模型。", fg="yellow", err=True)
    SETUP_HINT_MARKER.write_text("shown\n", encoding="utf-8")


def _invoked_cli_name() -> str:
    """Return the command name used by user."""
    cli_name = os.path.basename(sys.argv[0])
    if cli_name == CANONICAL_CLI_NAME:
        return cli_name
    return CANONICAL_CLI_NAME


@click.group(invoke_without_command=True)
@click.version_option(version=__version__, prog_name=CANONICAL_CLI_NAME)
@click.pass_context
def main(ctx: click.Context) -> None:
    """sageLLM: 面向国产算力的模块化大模型推理引擎

    为中国硬件生态提供类似 Ollama 的使用体验。

    \b
    快速开始:
      sagellm hello              # 🚀 一键推理测试
      sagellm info               # 查看系统信息
      sagellm run -p "Hello!"   # 运行推理
    """
    _maybe_show_setup_hint(ctx.invoked_subcommand)

    if ctx.invoked_subcommand is None:
        # No subcommand - show welcome message
        show_welcome_message(cli_name=CANONICAL_CLI_NAME)


# Register all commands (lazy import for faster startup)
def _register_commands():
    """Register all CLI commands."""
    # Import and register commands with error handling
    try:
        from .commands.hello import hello

        main.add_command(hello)
    except (ImportError, AttributeError) as e:
        import logging

        logging.debug("Failed to load hello command: %s", e)

    try:
        from .commands.run import chat, run

        main.add_command(run)
        main.add_command(chat)
    except (ImportError, AttributeError) as e:
        import logging

        logging.debug("Failed to load run commands: %s", e)

    try:
        from .commands.serve import serve

        main.add_command(serve)
    except (ImportError, AttributeError) as e:
        import logging

        logging.debug("Failed to load serve commands: %s", e)

    try:
        from .commands.demo import demo

        main.add_command(demo)
    except (ImportError, AttributeError) as e:
        import logging

        logging.debug("Failed to load demo command: %s", e)

    try:
        from .commands.config import config

        main.add_command(config)
    except (ImportError, AttributeError) as e:
        import logging

        logging.debug("Failed to load config command: %s", e)

    try:
        from .commands.info import info, version

        main.add_command(info)
        main.add_command(version)
    except (ImportError, AttributeError) as e:
        import logging

        logging.debug("Failed to load info commands: %s", e)

    try:
        from .commands.gateway import gateway

        main.add_command(gateway)
    except (ImportError, AttributeError) as e:
        import logging

        logging.debug("Failed to load gateway command: %s", e)

    # Install, profile, check, arch commands
    try:
        from .commands.install import install

        main.add_command(install)
    except (ImportError, AttributeError) as e:
        import logging

        logging.debug("Failed to load install command: %s", e)

    try:
        from .commands.profile import profile

        main.add_command(profile)
    except (ImportError, AttributeError) as e:
        import logging

        logging.debug("Failed to load profile command: %s", e)

    try:
        from .commands.check import check

        main.add_command(check)
    except (ImportError, AttributeError) as e:
        import logging

        logging.debug("Failed to load check command: %s", e)

    try:
        from .commands.arch import arch

        main.add_command(arch)
    except (ImportError, AttributeError) as e:
        import logging

        logging.debug("Failed to load arch command: %s", e)

    try:
        from .commands.env import env

        main.add_command(env)
    except (ImportError, AttributeError) as e:
        import logging

        logging.debug("Failed to load env command: %s", e)

    try:
        from .commands.sync import sync

        main.add_command(sync)
    except (ImportError, AttributeError) as e:
        import logging

        logging.debug("Failed to load sync command: %s", e)

    try:
        from .commands.ollama import ollama

        main.add_command(ollama)
    except (ImportError, AttributeError) as e:
        import logging

        logging.debug("Failed to load ollama command: %s", e)

    try:
        from .commands.setup import setup

        main.add_command(setup)
    except (ImportError, AttributeError) as e:
        import logging

        logging.debug("Failed to load setup command: %s", e)

    try:
        from .commands.embedding import embedding

        main.add_command(embedding)
    except (ImportError, AttributeError) as e:
        import logging

        logging.debug("Failed to load embedding command: %s", e)


# Register commands when module is imported
_register_commands()


if __name__ == "__main__":
    main()
