import json
from pathlib import Path

from django.apps import apps
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = '验证所有已安装插件的完整性和配置'

    def handle(self, *args, **options):
        app_config = apps.get_app_config('plugins')
        for plugin in app_config.get_active_plugins():
            self._validate_plugin_structure(plugin)
            self._check_plugin_meta(plugin)
            self.stdout.write(self.style.SUCCESS(f'插件 {plugin} 验证通过'))

    def _validate_plugin_structure(self, plugin_name):
        required_files = ['__init__.py', 'plugin_meta.json', 'models.py']
        plugin_path = Path('plugins') / plugin_name

        for file in required_files:
            if not (plugin_path / file).exists():
                raise FileNotFoundError(f'插件 {plugin_name} 缺少必需文件: {file}')

    def _check_plugin_meta(self, plugin_name):
        meta_path = Path('plugins') / plugin_name / 'plugin_meta.json'
        try:
            with meta_path.open(encoding='utf-8') as f:
                meta = json.load(f)
                if not all(k in meta for k in ['name', 'version', 'author']):
                    raise ValueError('插件元数据缺少必要字段')
        except json.JSONDecodeError:
            raise ValueError('plugin_meta.json 格式错误')
