"""
Configuration CLI Commands

Typer commands for configuration operations.
"""

import typer

from honeydb_ai.cli.app import get_console, get_config_service, initialize_logging
from honeydb_ai.controllers.config_controller import ConfigController


config_app = typer.Typer(
    name="config",
    help="Manage configuration",
    add_completion=False,
)


@config_app.command("show")
def show_config() -> None:
    """Show current configuration."""
    initialize_logging()

    console = get_console()
    config_service = get_config_service()
    config_controller = ConfigController(config_service, console)

    try:
        cfg = config_controller.load_config()
        config_controller.display_config(cfg)
    except Exception as e:
        console.print_error(f"Failed to show configuration: {e}")
        raise typer.Exit(1)


@config_app.command("set")
def set_config(
    key: str = typer.Argument(..., help="Configuration key"),
    value: str = typer.Argument(..., help="Configuration value"),
) -> None:
    """
    Set a configuration value.

    Examples:
        honeydb-ai config set openai_api_key sk-...
        honeydb-ai config set default_provider anthropic
        honeydb-ai config set temperature 0.8
    """
    initialize_logging()

    console = get_console()
    config_service = get_config_service()
    config_controller = ConfigController(config_service, console)

    try:
        # Handle different config keys
        if key == "honeydb_api_id":
            # Special handling: need to get both ID and key
            api_id = value
            current_config = config_service.load_config()
            api_key = current_config.honeydb_api_key or ""

            if not api_key:
                console.print_warning("HoneyDB API key not set. Set it with: honeydb-ai config set honeydb_api_key <key>")

            config_service.update_honeydb_credentials(api_id, api_key or "placeholder")
            console.print_success(f"Set honeydb_api_id")

        elif key == "honeydb_api_key":
            # Special handling: need to get both ID and key
            api_key = value
            current_config = config_service.load_config()
            api_id = current_config.honeydb_api_id or ""

            if not api_id:
                console.print_warning("HoneyDB API ID not set. Set it with: honeydb-ai config set honeydb_api_id <id>")

            config_service.update_honeydb_credentials(api_id or "placeholder", api_key)
            console.print_success(f"Set honeydb_api_key")

        elif key == "mcp_server_url":
            config_service.update_mcp_server_url(value)
            console.print_success(f"Set {key} = {value}")

        elif key.endswith("_api_key"):
            provider = key.replace("_api_key", "")
            config_controller.set_api_key(provider, value)

        elif key == "default_provider":
            config_controller.set_default_provider(value)

        elif key == "default_model":
            config_controller.set_default_model(value)

        elif key == "temperature":
            try:
                temp = float(value)
                config_controller.set_temperature(temp)
            except ValueError:
                console.print_error("Temperature must be a number")
                raise typer.Exit(1)

        elif key == "max_tokens":
            try:
                tokens = int(value) if value.lower() not in ["none", "null", ""] else None
                config_controller.set_max_tokens(tokens)
            except ValueError:
                console.print_error("Max tokens must be an integer")
                raise typer.Exit(1)

        elif key == "theme":
            config_controller.set_theme(value)

        elif key == "log_level":
            config_controller.set_log_level(value)

        elif key == "verbose_tool_calls":
            verbose = value.lower() in ["true", "yes", "y", "1", "on", "enabled"]
            config_controller.set_verbose_tool_calls(verbose)

        else:
            console.print_error(f"Unknown configuration key: {key}")
            console.print("\nAvailable keys:", style="info")
            console.print("  HoneyDB MCP: honeydb_api_id, honeydb_api_key, mcp_server_url")
            console.print("  LLM Providers: openai_api_key, anthropic_api_key, gemini_api_key")
            console.print("  LLM Settings: default_provider, default_model")
            console.print("  Parameters: temperature, max_tokens")
            console.print("  UI: theme, verbose_tool_calls, log_level")
            raise typer.Exit(1)

    except Exception as e:
        console.print_error(f"Failed to set configuration: {e}")
        raise typer.Exit(1)


@config_app.command("setup")
def setup_config() -> None:
    """Run interactive configuration setup."""
    initialize_logging()

    console = get_console()
    config_service = get_config_service()
    config_controller = ConfigController(config_service, console)

    try:
        config_controller.interactive_setup()
    except Exception as e:
        console.print_error(f"Setup failed: {e}")
        raise typer.Exit(1)


@config_app.command("path")
def show_config_path() -> None:
    """Show configuration file path."""
    initialize_logging()

    console = get_console()
    config_service = get_config_service()

    path = config_service.get_config_path()
    console.print(f"Configuration file: {path}", style="info")
