"""Global configuration management for GSD-RLM.

Stores user preferences in platform-specific config directory:
- Windows: C:\\Users\\<user>\\AppData\\Local\\gsd-rlm\\gsd-rlm\\
- macOS: /Users/<user>/Library/Application Support/gsd-rlm/
- Linux: /home/<user>/.config/gsd-rlm/

Requirements: GLOB-05 (global config), GLOB-06 (cross-platform)
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Optional

from platformdirs import user_config_dir, user_data_dir
from pydantic import BaseModel, Field


class GlobalConfig(BaseModel):
    """Global GSD-RLM configuration stored in user directory.

    Attributes:
        version: Config schema version for migration support
        default_provider: Default LLM provider (ollama, openai, anthropic, etc.)
        default_model: Default model name for the provider
        last_update_check: ISO timestamp of last version check
        commands_installed: Whether OpenCode commands have been installed
    """

    version: str = Field(default="1.0", description="Config schema version")
    default_provider: str = Field(default="ollama", description="Default LLM provider")
    default_model: str = Field(default="llama3.2", description="Default model name")
    last_update_check: Optional[str] = Field(
        default=None, description="Last update check timestamp"
    )
    commands_installed: bool = Field(
        default=False, description="Whether commands are installed"
    )

    model_config = {"extra": "forbid"}


def get_config_dir() -> Path:
    """Get the global config directory.

    Returns:
        Path to ~/.gsd-rlm/ or platform equivalent.
        Directory is created if it doesn't exist.
    """
    config_dir = Path(user_config_dir("gsd-rlm", "gsd-rlm"))
    config_dir.mkdir(parents=True, exist_ok=True)
    return config_dir


def get_data_dir() -> Path:
    """Get the global data directory for caches, etc.

    Returns:
        Path to data directory.
        Directory is created if it doesn't exist.
    """
    data_dir = Path(user_data_dir("gsd-rlm", "gsd-rlm"))
    data_dir.mkdir(parents=True, exist_ok=True)
    return data_dir


def get_config_path() -> Path:
    """Get the path to the config file.

    Returns:
        Path to config.json in config directory.
    """
    return get_config_dir() / "config.json"


def load_global_config() -> GlobalConfig:
    """Load global configuration from user directory.

    Returns:
        GlobalConfig instance (defaults if no config exists).
    """
    config_path = get_config_path()
    if config_path.exists():
        try:
            data = json.loads(config_path.read_text(encoding="utf-8"))
            return GlobalConfig(**data)
        except (json.JSONDecodeError, ValueError):
            # Corrupted config, return defaults
            pass
    return GlobalConfig()


def save_global_config(config: GlobalConfig) -> None:
    """Save global configuration to user directory.

    Args:
        config: GlobalConfig instance to save.
    """
    config_path = get_config_path()
    config_path.write_text(config.model_dump_json(indent=2), encoding="utf-8")
