"""CLI config management commands — extracted from cli.py.

This module contains the config_app subcommands for managing preLLM configuration.
"""

from __future__ import annotations

from pathlib import Path
from typing import Optional

import typer


config_app = typer.Typer(
    name="config",
    help="Manage preLLM configuration — API keys, models, defaults.",
    no_args_is_help=True,
)


@config_app.command("set")
def config_set_cmd(
    key: str = typer.Argument(..., help="Config key (e.g. openrouter-key, model, small-model, strategy)"),
    value: str = typer.Argument(..., help="Value to set"),
    global_: bool = typer.Option(False, "--global", "-g", help="Save to ~/.prellm/.env (user-wide) instead of project .env"),
):
    """Set a config value persistently.

    Saves to .env (project) or ~/.prellm/.env (--global).

    Examples:
        prellm config set openrouter-key sk-or-v1-abc123
        prellm config set model openrouter/moonshotai/kimi-k2.5
        prellm config set small-model ollama/qwen2.5:3b
        prellm config set strategy structure
        prellm config set openrouter-key sk-or-v1-abc123 --global
    """
    from llx.prellm.env_config import config_set, mask_value

    env_var, path = config_set(key, value, global_=global_)
    masked = mask_value(env_var, value)
    typer.echo(f"✅ {env_var}={masked}")
    typer.echo(f"   Saved to: {path}")


@config_app.command("get")
def config_get_cmd(
    key: str = typer.Argument(..., help="Config key (e.g. openrouter-key, model, small-model)"),
    raw: bool = typer.Option(False, "--raw", "-r", help="Show unmasked value"),
):
    """Get a config value.

    Examples:
        prellm config get openrouter-key
        prellm config get model
        prellm config get small-model
    """
    from llx.prellm.env_config import config_get, mask_value

    env_var, val, source = config_get(key)
    if val is None:
        typer.echo(f"✗ {env_var} — not set")
        typer.echo(f"   Set with: prellm config set {key} <value>")
        raise typer.Exit(1)
    displayed = val if raw else mask_value(env_var, val)
    typer.echo(f"{env_var}={displayed}")
    typer.echo(f"   Source: {source}")


def _format_config_sections(entries: dict) -> dict[str, list[str]]:
    """Group config entries into categorized sections for display."""
    sections: dict[str, list[str]] = {
        "🔑 API Keys": [],
        "🤖 Models": [],
        "⚙️  Settings": [],
        "📋 Other": [],
    }
    for var, info in entries.items():
        alias = f" ({info['alias']})" if info["alias"] else ""
        line = f"   {var}{alias} = {info['value']}  [{info['source']}]"
        if "API_KEY" in var or "SECRET" in var or var == "LITELLM_MASTER_KEY":
            sections["🔑 API Keys"].append(line)
        elif "MODEL" in var or "DEFAULT" in var:
            sections["🤖 Models"].append(line)
        elif var.startswith("PRELLM_"):
            sections["⚙️  Settings"].append(line)
        else:
            sections["📋 Other"].append(line)
    return sections


@config_app.command("list")
def config_list_cmd(
    raw: bool = typer.Option(False, "--raw", "-r", help="Show unmasked secret values"),
):
    """List all configured values.

    Example:
        prellm config list
        prellm config list --raw
    """
    from llx.prellm.env_config import config_list

    entries = config_list(show_secrets=raw)
    if not entries:
        typer.echo("No config values set.")
        typer.echo("   Set with: prellm config set <key> <value>")
        typer.echo("   Example:  prellm config set openrouter-key sk-or-v1-abc123")
        return

    typer.echo(f"\n🧠 preLLM Configuration")
    typer.echo(f"{'='*60}")

    for title, lines in _format_config_sections(entries).items():
        if lines:
            typer.echo(f"\n{title}:")
            for line in lines:
                typer.echo(line)

    typer.echo(f"\n{'='*60}")


@config_app.command("show")
def config_show_cmd():
    """Show effective configuration (resolved from all sources).

    Example:
        prellm config show
    """
    from llx.prellm.env_config import get_env_config

    env = get_env_config()
    typer.echo(f"\n🧠 preLLM Effective Configuration")
    typer.echo(f"{'='*60}")
    typer.echo(f"   Small LLM:     {env.small_model}")
    typer.echo(f"   Large LLM:     {env.large_model}")
    typer.echo(f"   Strategy:      {env.strategy}")
    typer.echo(f"   Server:        {env.host}:{env.port}")
    typer.echo(f"   Auth:          {'ON' if env.master_key else 'OFF'}")
    typer.echo(f"   Log level:     {env.log_level}")
    typer.echo(f"   Max tokens:    {env.max_tokens}")
    typer.echo(f"   Timeout:       {env.timeout}s")
    if env.fallbacks:
        typer.echo(f"   Fallbacks:     {', '.join(env.fallbacks)}")
    if env.monthly_budget:
        typer.echo(f"   Budget:        ${env.monthly_budget:.2f}/month")
    if env.config_path:
        typer.echo(f"   Config file:   {env.config_path}")

    typer.echo(f"\n🔌 Providers:")
    for name, info in env.providers.items():
        if info["has_key"] or name == "ollama":
            typer.echo(f"   ✓ {name.upper():14s} {info.get('base_url', '')}")
        else:
            typer.echo(f"   ✗ {name.upper():14s} ({info.get('key_var', '')} not set)")

    typer.echo(f"\n{'='*60}")


@config_app.command("init-env")
def config_init_env(
    global_: bool = typer.Option(False, "--global", "-g", help="Create ~/.prellm/.env instead of project .env"),
    force: bool = typer.Option(False, "--force", "-f", help="Overwrite existing file"),
):
    """Generate a starter .env file with all available settings.

    Example:
        prellm config init-env
        prellm config init-env --global
    """
    from llx.prellm.env_config import _resolve_config_path

    path = _resolve_config_path(global_)
    if path.is_file() and not force:
        typer.echo(f"⚠️  {path} already exists. Use --force to overwrite.")
        raise typer.Exit(1)

    path.parent.mkdir(parents=True, exist_ok=True)
    template = """\
# preLLM Configuration
# Generated by: prellm config init-env
# Docs: https://github.com/wronai/prellm

# ── Models ──────────────────────────────────────────────
PRELLM_SMALL_DEFAULT=ollama/qwen2.5:3b
PRELLM_LARGE_DEFAULT=gpt-4o-mini
PRELLM_STRATEGY=classify

# ── API Keys (uncomment and fill in) ───────────────────
# OPENAI_API_KEY=sk-...
# ANTHROPIC_API_KEY=sk-ant-...
# GROQ_API_KEY=gsk_...
# MISTRAL_API_KEY=...
# OPENROUTER_API_KEY=sk-or-v1-...
# DEEPSEEK_API_KEY=...
# TOGETHERAI_API_KEY=...
# GEMINI_API_KEY=...
# MOONSHOT_API_KEY=...

# ── Azure OpenAI ───────────────────────────────────────
# AZURE_API_KEY=...
# AZURE_API_BASE=https://your-resource.openai.azure.com
# AZURE_API_VERSION=2024-02-01

# ── AWS Bedrock ────────────────────────────────────────
# AWS_ACCESS_KEY_ID=...
# AWS_SECRET_ACCESS_KEY=...
# AWS_REGION_NAME=us-east-1

# ── Ollama (local) ─────────────────────────────────────
# OLLAMA_API_BASE=http://localhost:11434

# ── OpenRouter ─────────────────────────────────────────
# OPENROUTER_API_BASE=https://openrouter.ai/api/v1

# ── Server ─────────────────────────────────────────────
# PRELLM_HOST=0.0.0.0
# PRELLM_PORT=8080
# PRELLM_LOG_LEVEL=info
# LITELLM_MASTER_KEY=sk-prellm-...

# ── Limits ─────────────────────────────────────────────
# PRELLM_MAX_TOKENS=4096
# PRELLM_TIMEOUT=30
# PRELLM_MONTHLY_BUDGET=50.00
# PRELLM_FALLBACKS=ollama/llama3:8b,gpt-4o-mini
"""
    with open(path, "w") as f:
        f.write(template)

    typer.echo(f"✅ Created {path}")
    typer.echo(f"   Edit the file to add your API keys.")
