# llm_manager/config.py
"""配置管理模块 - 处理持久化存储"""

import json
import os
from pathlib import Path
from typing import Optional
from dataclasses import dataclass, asdict, field


@dataclass
class APIEndpoint:
    """单个 API 端点配置"""
    name: str
    url: str
    token: str
    models: list[str] = field(default_factory=list)
    
    def to_dict(self) -> dict:
        return asdict(self)
    
    @classmethod
    def from_dict(cls, data: dict) -> "APIEndpoint":
        return cls(**data)


class ConfigManager:
    """配置管理器 - 处理持久化存储"""
    
    def __init__(self, config_dir: Optional[Path] = None):
        if config_dir is None:
            # 使用 XDG 规范的用户配置目录
            xdg_config = os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config"))
            self.config_dir = Path(xdg_config) / "llm-manager"
        else:
            self.config_dir = Path(config_dir)
        
        self.config_file = self.config_dir / "endpoints.json"
        self._ensure_config_dir()
        self._endpoints: dict[str, APIEndpoint] = {}
        self._load()
    
    def _ensure_config_dir(self):
        """确保配置目录存在"""
        self.config_dir.mkdir(parents=True, exist_ok=True)
    
    def _load(self):
        """从文件加载配置"""
        if self.config_file.exists():
            try:
                with open(self.config_file, "r", encoding="utf-8") as f:
                    data = json.load(f)
                    for name, endpoint_data in data.get("endpoints", {}).items():
                        self._endpoints[name] = APIEndpoint.from_dict(endpoint_data)
            except (json.JSONDecodeError, KeyError) as e:
                print(f"警告: 配置文件损坏，将创建新配置: {e}")
                self._endpoints = {}
    
    def _save(self):
        """保存配置到文件"""
        data = {
            "endpoints": {name: ep.to_dict() for name, ep in self._endpoints.items()}
        }
        with open(self.config_file, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2, ensure_ascii=False)
    
    def add_endpoint(self, endpoint: APIEndpoint) -> bool:
        """添加或更新端点"""
        self._endpoints[endpoint.name] = endpoint
        self._save()
        return True
    
    def remove_endpoint(self, name: str) -> bool:
        """删除端点"""
        if name in self._endpoints:
            del self._endpoints[name]
            self._save()
            return True
        return False
    
    def get_endpoint(self, name: str) -> Optional[APIEndpoint]:
        """获取指定端点"""
        return self._endpoints.get(name)
    
    def get_all_endpoints(self) -> dict[str, APIEndpoint]:
        """获取所有端点"""
        return self._endpoints.copy()
    
    def get_all_models(self) -> list[tuple[str, str]]:
        """获取所有模型列表，返回 (endpoint_name, model_name) 元组"""
        models = []
        for name, endpoint in self._endpoints.items():
            for model in endpoint.models:
                models.append((name, model))
        return models
    
    def update_models(self, name: str, models: list[str]):
        """更新端点的模型列表"""
        if name in self._endpoints:
            self._endpoints[name].models = models
            self._save()
