"""Configuration management for MangoDesk CLI.

Stores configuration in ~/.mangodesk/config.json
"""

import json
from pathlib import Path
from typing import Any


CONFIG_DIR = Path.home() / ".mangodesk"
CONFIG_FILE = CONFIG_DIR / "config.json"

DEFAULT_CONFIG = {
    "API_URL": "https://mangodesk-api-ezq8.onrender.com",
    "MANGO_API_KEY": None,
    "ANTHROPIC_API_KEY": None,
}


def ensure_config_dir() -> None:
    """Ensure the config directory exists."""
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)


def load_config() -> dict[str, Any]:
    """Load configuration from file."""
    ensure_config_dir()

    if not CONFIG_FILE.exists():
        return DEFAULT_CONFIG.copy()

    try:
        with open(CONFIG_FILE) as f:
            config = json.load(f)
        # Merge with defaults to handle new keys
        return {**DEFAULT_CONFIG, **config}
    except (json.JSONDecodeError, IOError):
        return DEFAULT_CONFIG.copy()


def save_config(config: dict[str, Any]) -> None:
    """Save configuration to file."""
    ensure_config_dir()

    with open(CONFIG_FILE, "w") as f:
        json.dump(config, f, indent=2)


def get_config(key: str) -> Any:
    """Get a configuration value."""
    config = load_config()
    return config.get(key)


def set_config(key: str, value: Any) -> None:
    """Set a configuration value."""
    config = load_config()
    config[key] = value
    save_config(config)


def get_api_url() -> str:
    """Get the API URL."""
    return get_config("API_URL") or DEFAULT_CONFIG["API_URL"]


def get_api_key() -> str | None:
    """Get the Mango API key."""
    return get_config("MANGO_API_KEY")


def get_anthropic_api_key() -> str | None:
    """Get the Anthropic API key."""
    return get_config("ANTHROPIC_API_KEY")
