#!/usr/bin/env python3
"""
Configuration management for agata.

Stores user preferences like default models in ~/.config/agata/config.yaml
"""

import os
import yaml
from typing import Dict, Optional
from pathlib import Path

CONFIG_DIR = Path.home() / ".config" / "agata"
CONFIG_FILE = CONFIG_DIR / "config.yaml"

# Built-in defaults (used when no config exists)
BUILTIN_DEFAULTS = {
    "default_models": {"openrouter": "openai/gpt-5-nano", "ollama": "llama3.2"},
    "default_provider": "openrouter",
    "preferred_models": [
        "openai/gpt-5-nano",
        "qwen/qwen3-next-80b-a3b-instruct:free",
        "openai/gpt-5.4",
        "inception/mercury-2",
        "google/gemini-3.1-flash-image-preview",
        "z-ai/glm-5",
        "moonshotai/kimi-k2.5",
    ],
}

# Default system prompt (without timestamp - injected at runtime)
DEFAULT_SYSTEM_PROMPT = "I am your professional, timesaving, truthful, useful and efficient assistant. It is {timestamp} now. I provide brief and clear responses, I do not repeat neither myself nor you."


def _ensure_config_dir():
    """Ensure the config directory exists."""
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)


def load_config() -> Dict:
    """
    Load configuration from file or return defaults.
    If file doesn't exist, creates it with built-in defaults.

    Returns:
        Configuration dictionary
    """
    if not CONFIG_FILE.exists():
        # Create config file with defaults
        save_config(BUILTIN_DEFAULTS.copy())
        return BUILTIN_DEFAULTS.copy()

    try:
        with open(CONFIG_FILE, "r") as f:
            config = yaml.safe_load(f) or {}
            # Merge with defaults to ensure all keys exist
            merged = BUILTIN_DEFAULTS.copy()
            merged.update(config)
            # Save merged config if new keys were added
            if set(merged.keys()) != set(config.keys()):
                save_config(merged)
            return merged
    except Exception:
        return BUILTIN_DEFAULTS.copy()


def save_config(config: Dict):
    """
    Save configuration to file.

    Args:
        config: Configuration dictionary to save
    """
    _ensure_config_dir()
    with open(CONFIG_FILE, "w") as f:
        yaml.dump(config, f, default_flow_style=False, sort_keys=True)


def get_default_model(provider: str) -> str:
    """
    Get the default model for a provider from config.

    Args:
        provider: Provider name ('openrouter' or 'ollama')

    Returns:
        Default model name
    """
    config = load_config()
    return config.get("default_models", {}).get(
        provider, BUILTIN_DEFAULTS["default_models"][provider]
    )


def set_default_model(provider: str, model: str):
    """
    Set the default model for a provider.

    Args:
        provider: Provider name ('openrouter' or 'ollama')
        model: Model identifier (e.g., 'openai/gpt-4')
    """
    config = load_config()
    if "default_models" not in config:
        config["default_models"] = {}
    config["default_models"][provider] = model
    save_config(config)


def get_default_provider() -> str:
    """
    Get the default provider from config.

    Returns:
        Default provider name
    """
    config = load_config()
    return config.get("default_provider", BUILTIN_DEFAULTS["default_provider"])


def set_default_provider(provider: str):
    """
    Set the default provider.

    Args:
        provider: Provider name ('openrouter' or 'ollama')
    """
    config = load_config()
    config["default_provider"] = provider
    save_config(config)


def get_preferred_models() -> list:
    """
    Get the list of preferred models from config.

    Returns:
        List of preferred model identifiers
    """
    config = load_config()
    return config.get("preferred_models", BUILTIN_DEFAULTS["preferred_models"])


def set_preferred_models(models: list):
    """
    Set the list of preferred models.

    Args:
        models: List of model identifiers
    """
    config = load_config()
    config["preferred_models"] = models
    save_config(config)


def add_preferred_model(model: str):
    """
    Add a model to the preferred models list.

    Args:
        model: Model identifier to add
    """
    config = load_config()
    if "preferred_models" not in config:
        config["preferred_models"] = []
    if model not in config["preferred_models"]:
        config["preferred_models"].append(model)
        save_config(config)


def remove_preferred_model(model: str):
    """
    Remove a model from the preferred models list.

    Args:
        model: Model identifier to remove
    """
    config = load_config()
    if "preferred_models" in config and model in config["preferred_models"]:
        config["preferred_models"].remove(model)
        save_config(config)


def reset_to_defaults():
    """Reset configuration to built-in defaults."""
    save_config(BUILTIN_DEFAULTS.copy())


def get_system_prompt() -> str:
    """
    Get the system prompt template from config.
    If not set, returns the default prompt template.
    The timestamp placeholder {timestamp} will be replaced at runtime.

    Returns:
        System prompt template string
    """
    config = load_config()
    return config.get("system_prompt", DEFAULT_SYSTEM_PROMPT)


def set_system_prompt(prompt: str):
    """
    Set a custom system prompt template.
    Use {timestamp} placeholder where the current timestamp should be inserted.

    Args:
        prompt: System prompt template string
    """
    config = load_config()
    config["system_prompt"] = prompt
    save_config(config)


def format_system_prompt(template: str = None) -> str:
    """
    Format the system prompt template with the current timestamp.

    Args:
        template: Prompt template (uses config value if None)

    Returns:
        Formatted system prompt with current timestamp
    """
    import datetime as dt

    if template is None:
        template = get_system_prompt()

    return template.format(timestamp=dt.datetime.now().isoformat())


def reset_system_prompt():
    """Reset system prompt to default."""
    config = load_config()
    if "system_prompt" in config:
        del config["system_prompt"]
        save_config(config)
