# -*- coding: utf-8 -*-
"""
配置管理器
管理飞书等外部系统的配置信息，支持持久化存储和并发访问
"""

import json
import os
import threading
import logging
from typing import Dict, Any, Optional
from datetime import datetime
from pathlib import Path

logger = logging.getLogger(__name__)

class ConfigManager:
    """配置管理器"""
    
    _instance = None
    _lock = threading.Lock()
    
    def __new__(cls):
        """单例模式"""
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super(ConfigManager, cls).__new__(cls)
                    cls._instance._initialized = False
        return cls._instance
    
    def __init__(self):
        if self._initialized:
            return
        
        self._config_lock = threading.RLock()
        self.config_file = Path("config/integrations_config.json")
        self.config_file.parent.mkdir(exist_ok=True)
        
        # 默认配置
        self.default_config = {
            "feishu": {
                "app_id": "",
                "app_secret": "",
                "app_token": "",
                "table_id": "",
                "last_updated": None,
                "status": "inactive"
            },
            "system": {
                "sync_limit": 10,
                "ai_suggestions_enabled": True,
                "auto_sync_interval": 0,  # 0表示不自动同步
                "last_sync_time": None
            }
        }
        
        self._load_config()
        self._initialized = True
    
    def _load_config(self):
        """加载配置文件"""
        try:
            if self.config_file.exists():
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    loaded_config = json.load(f)
                    # 合并默认配置和加载的配置
                    self.config = self._merge_configs(self.default_config, loaded_config)
            else:
                self.config = self.default_config.copy()
                self._save_config()
            logger.info("配置加载成功")
        except Exception as e:
            logger.error(f"配置加载失败: {e}")
            self.config = self.default_config.copy()
    
    def _save_config(self):
        """保存配置文件"""
        try:
            with self._config_lock:
                with open(self.config_file, 'w', encoding='utf-8') as f:
                    json.dump(self.config, f, ensure_ascii=False, indent=2)
            logger.info("配置保存成功")
        except Exception as e:
            logger.error(f"配置保存失败: {e}")
    
    def _merge_configs(self, default: Dict, loaded: Dict) -> Dict:
        """合并配置，确保所有必要的键都存在"""
        result = default.copy()
        for key, value in loaded.items():
            if isinstance(value, dict) and key in result:
                result[key] = self._merge_configs(result[key], value)
            else:
                result[key] = value
        return result
    
    def get_feishu_config(self) -> Dict[str, Any]:
        """获取飞书配置"""
        with self._config_lock:
            return self.config.get("feishu", {}).copy()
    
    def update_feishu_config(self, **kwargs) -> bool:
        """更新飞书配置"""
        try:
            with self._config_lock:
                feishu_config = self.config.setdefault("feishu", {})
                
                # 更新配置项
                for key, value in kwargs.items():
                    if key in ["app_id", "app_secret", "app_token", "table_id"]:
                        feishu_config[key] = value
                
                # 更新状态和时间戳
                feishu_config["last_updated"] = datetime.now().isoformat()
                feishu_config["status"] = "active" if all([
                    feishu_config.get("app_id"),
                    feishu_config.get("app_secret"),
                    feishu_config.get("app_token"),
                    feishu_config.get("table_id")
                ]) else "inactive"
                
                self._save_config()
                logger.info("飞书配置更新成功")
                return True
        except Exception as e:
            logger.error(f"飞书配置更新失败: {e}")
            return False
    
    def get_system_config(self) -> Dict[str, Any]:
        """获取系统配置"""
        with self._config_lock:
            return self.config.get("system", {}).copy()
    
    def update_system_config(self, **kwargs) -> bool:
        """更新系统配置"""
        try:
            with self._config_lock:
                system_config = self.config.setdefault("system", {})
                
                for key, value in kwargs.items():
                    if key in ["sync_limit", "ai_suggestions_enabled", "auto_sync_interval"]:
                        system_config[key] = value
                
                self._save_config()
                logger.info("系统配置更新成功")
                return True
        except Exception as e:
            logger.error(f"系统配置更新失败: {e}")
            return False
    
    def test_feishu_connection(self) -> Dict[str, Any]:
        """测试飞书连接"""
        try:
            from .feishu_client import FeishuClient
            
            feishu_config = self.get_feishu_config()
            if not all([feishu_config.get("app_id"), feishu_config.get("app_secret")]):
                return {"success": False, "error": "飞书配置不完整"}
            
            client = FeishuClient(feishu_config["app_id"], feishu_config["app_secret"])
            
            # 测试获取访问令牌
            token = client._get_access_token()
            if token:
                return {"success": True, "message": "飞书连接正常"}
            else:
                return {"success": False, "error": "无法获取访问令牌"}
                
        except Exception as e:
            logger.error(f"飞书连接测试失败: {e}")
            return {"success": False, "error": str(e)}
    
    def get_config_summary(self) -> Dict[str, Any]:
        """获取配置摘要"""
        with self._config_lock:
            feishu_config = self.config.get("feishu", {})
            system_config = self.config.get("system", {})
            
            return {
                "feishu": {
                    "app_id": feishu_config.get("app_id", ""),
                    "app_token": feishu_config.get("app_token", ""),
                    "table_id": feishu_config.get("table_id", ""),
                    "status": feishu_config.get("status", "inactive"),
                    "last_updated": feishu_config.get("last_updated"),
                    "app_secret": "***" if feishu_config.get("app_secret") else ""
                },
                "system": {
                    "sync_limit": system_config.get("sync_limit", 10),
                    "ai_suggestions_enabled": system_config.get("ai_suggestions_enabled", True),
                    "auto_sync_interval": system_config.get("auto_sync_interval", 0),
                    "last_sync_time": system_config.get("last_sync_time")
                }
            }
    
    def reset_config(self) -> bool:
        """重置配置为默认值"""
        try:
            with self._config_lock:
                self.config = self.default_config.copy()
                self._save_config()
                logger.info("配置重置成功")
                return True
        except Exception as e:
            logger.error(f"配置重置失败: {e}")
            return False
    
    def export_config(self) -> str:
        """导出配置（用于备份）"""
        with self._config_lock:
            return json.dumps(self.config, ensure_ascii=False, indent=2)
    
    def import_config(self, config_json: str) -> bool:
        """导入配置（用于恢复）"""
        try:
            imported_config = json.loads(config_json)
            with self._config_lock:
                self.config = self._merge_configs(self.default_config, imported_config)
                self._save_config()
                logger.info("配置导入成功")
                return True
        except Exception as e:
            logger.error(f"配置导入失败: {e}")
            return False

# 全局配置管理器实例
config_manager = ConfigManager()
