"""Environment variable management command."""

from __future__ import annotations

import logging
import os

import click

from ..utils.console import get_console
from ..utils.env_detector import EnvInitializer

logger = logging.getLogger(__name__)


@click.group()
def env() -> None:
    """Manage sageLLM environment variables.

    \b
    Examples:
        sagellm env show               # Show current environment variables
        sagellm env export             # Export as shell commands
        eval "$(sagellm env export)"   # Apply to current shell session
    """
    pass


@env.command()
def show() -> None:
    """Show current sageLLM environment variables."""
    console = get_console()
    env_info = EnvInitializer.get_env_info()

    console.print("[bold]📋 sageLLM 环境变量[/bold]\n")

    for category, vars_dict in env_info.items():
        console.print(f"[bold cyan]{category}[/bold cyan]:")
        for var_name, var_value in vars_dict.items():
            console.print(f"  {var_name}={var_value}")
        console.print()


@env.command()
def export() -> None:
    """Export environment variables as shell commands.

    Output can be sourced in a shell:
        eval "$(sagellm env export)"
    """
    env_info = EnvInitializer.get_env_info()

    # Flatten the nested dict
    all_vars = {}
    for _category, vars_dict in env_info.items():
        all_vars.update(vars_dict)

    # Output as shell export commands (without color codes)
    # This is meant to be sourced, so we output raw text
    for var_name, var_value in sorted(all_vars.items()):
        if var_value and var_value != "Not set":
            # Properly escape for shell
            escaped_value = var_value.replace('"', '\\"')
            print(f'export {var_name}="{escaped_value}"')


@env.command()
def init() -> None:
    """Explicitly initialize all environment variables with network detection.

    This performs actual network connectivity tests to determine the best
    HuggingFace endpoint. Use this when you want to refresh the configuration.
    """
    console = get_console()

    console.print("[cyan]🔄 正在检测环境变量...[/cyan]")
    console.print()

    # Show network detection process
    from ..utils.env_detector import NetworkDetector

    console.print(
        f"[cyan]🔍 检测 HuggingFace 官方端点 (超时: {NetworkDetector.TIMEOUT}s)...[/cyan]"
    )
    official_ok = NetworkDetector.check_connectivity(
        NetworkDetector.HF_OFFICIAL, timeout=NetworkDetector.TIMEOUT
    )
    if official_ok:
        console.print(f"✅ 官方端点可达: {NetworkDetector.HF_OFFICIAL}")
        os.environ["HF_ENDPOINT"] = NetworkDetector.HF_OFFICIAL
    else:
        console.print("⚠️  官方端点不可达，使用镜像")
        console.print(f"🪞 镜像: {NetworkDetector.HF_MIRROR}")
        os.environ["HF_ENDPOINT"] = NetworkDetector.HF_MIRROR

    # Initialize other env vars (no network needed)
    EnvInitializer.init_hf_cache_dir()
    EnvInitializer.init_model_cache_dir()
    EnvInitializer.init_logging_level()

    # Save to profile
    EnvInitializer.save_env_profile()

    console.print()
    console.print("[green]✅ 环境变量已检测并保存[/green]")
    console.print()

    # Show the snapshot
    env_info = EnvInitializer.get_env_info()
    for _category, vars_dict in env_info.items():
        for var_name, var_value in vars_dict.items():
            console.print(f"  [cyan]{var_name}[/cyan] = [green]{var_value}[/green]")

    console.print()
    console.print("[dim]💡 提示：运行以下命令将环境变量导入到当前 shell：[/dim]")
    console.print('  [cyan]eval "$(sagellm env export)"[/cyan]')
