from typing import Dict, Any, Callable
from fastapi import FastAPI
import json
import os
from .decorators import singleton


@singleton
class PluginManager:
    """插件管理器，用于管理FastAPI插件"""

    def __init__(self, app: FastAPI):
        self.app = app
        self.plugins: Dict[str, Any] = {}
        self.configs: Dict[str, Dict] = {}

    def load_config(self, plugin_name: str, config_path: str) -> Dict:
        """加载插件配置文件"""
        if os.path.exists(config_path):
            with open(config_path, "r") as f:
                config = json.load(f)
                self.configs[plugin_name] = config
                return config
        return {}

    def register_plugin(
        self, name: str, init_func: Callable, config: Dict = None
    ) -> None:
        """注册插件"""
        try:
            plugin_instance = init_func(self.app, config or self.configs.get(name, {}))
            self.plugins[name] = plugin_instance
        except Exception as e:
            print(f"Failed to register plugin {name}: {e}")

    def get_plugin(self, name: str) -> Any:
        """获取已注册的插件"""
        return self.plugins.get(name)

    def get_config(self, plugin_name: str) -> Dict:
        """获取插件配置"""
        return self.configs.get(plugin_name, {})
