import json
import os
import sys
from importlib import import_module
from pathlib import Path

from django.apps import AppConfig
from django.conf import settings


class PluginsConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'apps.plugin_manager'
    verbose_name = '插件管理'

    def ready(self):
        """仅保留插件目录初始化和admin加载"""
        if os.environ.get('RUN_MAIN') == 'true' or 'runserver' not in sys.argv:
            self._ensure_plugins_dir()
            # self._load_plugin_admins()

    def _ensure_plugins_dir(self):
        """确保插件目录存在"""
        (Path(settings.BASE_DIR) / 'plugins').mkdir(exist_ok=True)

    def _load_plugin_admins(self):
        """加载插件admin配置"""
        for plugin in self.get_active_plugins():
            try:
                import_module(f'plugins.{plugin}.admin')
            except ImportError:
                continue

    def get_active_plugins(self):
        """获取所有激活的插件"""
        active_plugins = []
        plugins_dir = Path(settings.BASE_DIR) / 'plugins'
        for plugin_dir in plugins_dir.iterdir():
            meta_file = plugin_dir / 'plugin_meta.json'
            if meta_file.exists():
                try:
                    with meta_file.open(encoding='utf-8') as f:
                        if json.load(f).get('is_active', False):
                            active_plugins.append(plugin_dir.name)
                except (json.JSONDecodeError, KeyError):
                    continue
        return active_plugins
