"""Configuration management for SurfAI."""

import json
import os
from pathlib import Path
from typing import Optional

from pydantic import BaseModel, Field


class ModelConfig(BaseModel):
    """Configuration for a specific LLM provider."""
    api_key: str
    base_url: Optional[str] = None
    model_name: Optional[str] = None


class Config(BaseModel):
    """SurfAI configuration."""
    default_model: str = "kimi"
    models: dict[str, ModelConfig] = Field(default_factory=dict)
    
    @classmethod
    def get_config_dir(cls) -> Path:
        """Get the configuration directory."""
        config_dir = Path.home() / ".surfai"
        config_dir.mkdir(parents=True, exist_ok=True)
        return config_dir
    
    @classmethod
    def get_config_path(cls) -> Path:
        """Get the configuration file path."""
        return cls.get_config_dir() / "config.json"
    
    @classmethod
    def load(cls) -> "Config":
        """Load configuration from file."""
        config_path = cls.get_config_path()
        if config_path.exists():
            with open(config_path, "r", encoding="utf-8") as f:
                data = json.load(f)
                # Convert nested dicts to ModelConfig objects
                if "models" in data:
                    data["models"] = {
                        k: ModelConfig(**v) if isinstance(v, dict) else v
                        for k, v in data["models"].items()
                    }
                return cls(**data)
        return cls()
    
    def save(self) -> None:
        """Save configuration to file."""
        config_path = self.get_config_path()
        with open(config_path, "w", encoding="utf-8") as f:
            json.dump(self.model_dump(), f, indent=2, ensure_ascii=False)
    
    def set_model(self, name: str, api_key: str, base_url: Optional[str] = None) -> None:
        """Set configuration for a model."""
        self.models[name] = ModelConfig(api_key=api_key, base_url=base_url)
        self.save()
    
    def get_model_config(self, name: Optional[str] = None) -> Optional[ModelConfig]:
        """Get configuration for a model."""
        name = name or self.default_model
        return self.models.get(name)
    
    def set_default_model(self, name: str) -> None:
        """Set the default model."""
        if name not in self.models:
            raise ValueError(f"Model '{name}' not configured. Run: surfai config --model {name} --key <key>")
        self.default_model = name
        self.save()
