"""Configuration management for mykb (~/.mykb/config.toml)."""

import os
from pathlib import Path

import tomli
import tomli_w


_config_dir: Path | None = None


def get_config_dir() -> Path:
    if _config_dir is not None:
        return _config_dir
    return Path(os.environ.get('MYKB_CONFIG_DIR', '~/.mykb')).expanduser()


def set_config_dir(path: Path):
    global _config_dir
    _config_dir = path


def get_config_file() -> Path:
    return get_config_dir() / 'config.toml'


def get_state_file() -> Path:
    return get_config_dir() / 'state.json'


DEFAULT_CONFIG = {
    'backend': {
        'type': 'meilisearch',
        'meilisearch': {
            'url': 'http://localhost:7700',
            'api_key': '',
        },
        'seekdb': {
            'path': '~/.mykb/seekdb.db',
            'database': 'mykb',
            'fulltext_analyzer': 'ik',  # ik | space | ngram
        },
    },
    # Legacy key for backward compatibility
    'meilisearch': {
        'url': 'http://localhost:7700',
        'api_key': '',
    },
    'embedding': {
        'model': 'google/embeddinggemma-300m',
        'chunk_size': 800,
        'chunk_overlap': 0.15,
    },
    'collections': {},
}


def ensure_config_dir():
    get_config_dir().mkdir(parents=True, exist_ok=True)


def load_config() -> dict:
    config_file = get_config_file()
    if not config_file.exists():
        return dict(DEFAULT_CONFIG)
    with open(config_file, 'rb') as f:
        return tomli.load(f)


def save_config(config: dict):
    ensure_config_dir()
    config_file = get_config_file()
    with open(config_file, 'wb') as f:
        tomli_w.dump(config, f)


def get_config() -> dict:
    """Load config, merging with defaults for missing keys."""
    config = load_config()
    # Merge defaults for top-level sections
    for key, default_val in DEFAULT_CONFIG.items():
        if key not in config:
            config[key] = default_val
        elif isinstance(default_val, dict) and key != 'collections':
            for sub_key, sub_val in default_val.items():
                if sub_key not in config[key]:
                    config[key][sub_key] = sub_val
    return config


def get_meilisearch_config() -> dict:
    """Get Meilisearch config (legacy, prefer get_backend_config)."""
    config = get_config()
    return config['meilisearch']


def get_embedding_config() -> dict:
    config = get_config()
    return config['embedding']


def get_backend_config() -> tuple[str, dict]:
    """
    Get backend type and config.
    Returns: (backend_type, backend_config_dict)

    Supports both new [backend] format and legacy [meilisearch] format.
    """
    # Use load_config to check raw file content (not merged with defaults)
    raw_config = load_config()

    # New format: [backend] section explicitly in config file
    if 'backend' in raw_config and 'type' in raw_config['backend']:
        backend_type = raw_config['backend']['type']
        # Merge with defaults for the specific backend type
        backend_defaults = DEFAULT_CONFIG.get('backend', {}).get(backend_type, {})
        backend_config = dict(backend_defaults)
        backend_config.update(raw_config['backend'].get(backend_type, {}))
        return backend_type, backend_config

    # Legacy format: [meilisearch] at top level (without [backend] section)
    if 'meilisearch' in raw_config and 'backend' not in raw_config:
        # Merge with defaults
        config = dict(DEFAULT_CONFIG['meilisearch'])
        config.update(raw_config['meilisearch'])
        return 'meilisearch', config

    # Fallback to defaults
    return 'meilisearch', DEFAULT_CONFIG['backend']['meilisearch']
