"""
配置管理模块
"""
import json
import os
from typing import Any, Dict, Optional


class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_dir: str = None):
        if config_dir is None:
            config_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "config")
        self.config_dir = config_dir
        self.config_file = os.path.join(config_dir, "config.json")
        self._config: Dict[str, Any] = {}
        self._load_config()
    
    def _load_config(self):
        """加载配置文件"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    self._config = json.load(f)
            except Exception as e:
                print(f"加载配置文件失败: {e}")
                self._config = self._get_default_config()
        else:
            self._config = self._get_default_config()
            self._save_config()
    
    def _save_config(self):
        """保存配置文件"""
        os.makedirs(self.config_dir, exist_ok=True)
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self._config, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存配置文件失败: {e}")
    
    def _get_default_config(self) -> Dict[str, Any]:
        """获取默认配置"""
        return {
            "app": {
                "name": "ClawSpy",
                "version": "1.0.0"
            },
            "data": {
                "data_dir": "data",
                "db_path": "data/clawspy.db"
            },
            "logging": {
                "log_dir": "logs",
                "log_level": "INFO"
            },
            "spiders": {
                "enabled_platforms": [],
                "interval_seconds": 3600
            },
            "semantic": {
                "engine": "default",
                "threshold": 0.5
            },
            "industry": {
                "selected_industries": [],
                "custom_keywords": {}
            }
        }
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值"""
        keys = key.split('.')
        value = self._config
        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            else:
                return default
        return value
    
    def set(self, key: str, value: Any):
        """设置配置值"""
        keys = key.split('.')
        config = self._config
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
        config[keys[-1]] = value
        self._save_config()
    
    def get_all(self) -> Dict[str, Any]:
        """获取所有配置"""
        return self._config.copy()


_config_manager: Optional[ConfigManager] = None


def get_config() -> ConfigManager:
    """获取配置管理器单例"""
    global _config_manager
    if _config_manager is None:
        _config_manager = ConfigManager()
    return _config_manager


def set(key: str, value: Any):
    """设置配置（便捷方法）"""
    get_config().set(key, value)


def get(key: str, default: Any = None) -> Any:
    """获取配置（便捷方法）"""
    return get_config().get(key, default)
