# -*- coding: utf-8 -*-
"""
配置加载器 - 统一加载所有JSON配置文件

合并了原来的 json_loader.py 和 taxonomy_loader.py
"""

import json
import os
from pathlib import Path
from typing import Dict, List


class ConfigLoader:
    """统一的配置加载器"""
    
    # 控制是否输出调试信息
    debug_mode = False
    
    def __init__(self):
        """初始化加载器"""
        # 获取项目根目录
        self.project_root = Path(__file__).parent.parent.parent.parent
        self.config_dir = self.project_root / "config" / "data"
        
        # 漏洞库路径（使用新目录结构 ge10/web/data/，支持多种文件名）
        self.web_data_dir = self.project_root / "ge10" / "web" / "data"
        
        # 缓存数据
        self._vulnerability_db = None
        
        # 加载漏洞库数据（用于某些旧功能，新功能从数据库读取）
        self._load_vulnerability_db()
    
    def _load_json_file(self, file_path: Path) -> Dict:
        """加载JSON文件的通用方法"""
        try:
            if self.debug_mode:
                print(f"正在加载JSON文件: {file_path}")
            
            if not file_path.exists():
                if self.debug_mode:
                    print(f"文件不存在: {file_path}")
                return None
            
            with open(file_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
                if self.debug_mode:
                    print(f"成功加载JSON文件")
                return data
        except json.JSONDecodeError as e:
            if self.debug_mode:
                print(f"JSON解析错误 {file_path}: {str(e)}")
            return None
        except Exception as e:
            if self.debug_mode:
                print(f"加载JSON文件出错 {file_path}: {str(e)}")
            return None
    
    def _load_vulnerability_db(self):
        """加载漏洞库数据（支持自动检测多种文件名）"""
        # 支持多种可能的文件名（更开放和灵活）
        possible_filenames = [
            'vulnerability_db.json',      # Web方向标准名称
            'web_knowledge_db.json',      # 带方向前缀
            'web_db.json',                # 简化名称
            'knowledge_db.json',           # 通用名称
        ]
        
        load_path = None
        if self.web_data_dir.exists():
            for filename in possible_filenames:
                test_path = self.web_data_dir / filename
                if test_path.exists():
                    load_path = test_path
                    break

        if not load_path:
            print(f"⚠️ 未找到漏洞库文件（已检查目录：{self.web_data_dir}）")
            print(f"   尝试的文件名：{', '.join(possible_filenames)}")
            self._vulnerability_db = {"vulnerabilities": {}}
            return

        data = self._load_json_file(load_path)
        if data and "vulnerabilities" in data:
            self._vulnerability_db = data
            print(f"✅ 已加载漏洞库数据: {len(data['vulnerabilities'])} 个漏洞类型（来源：{load_path.name}）")
        else:
            self._vulnerability_db = {"vulnerabilities": {}}
    
    def get_vulnerabilities_for_display(self) -> Dict:
        """获取用于前端显示的漏洞数据结构（从 vulnerability_db.json）"""
        vulnerabilities = self._vulnerability_db.get("vulnerabilities", {})
        
        # 按 category 分组
        category_map = {}
        for vuln_name, vuln_data in vulnerabilities.items():
            category = vuln_data.get("category", "其他")
            if category not in category_map:
                category_map[category] = []
            category_map[category].append({
                'id': vuln_name,
                'name': vuln_name,
                'languages': vuln_data.get('languages', [])
            })
        
        # 转换为列表格式
        categories = []
        for category_name, vulns in category_map.items():
            categories.append({
                'id': category_name,
                'name': category_name,
                'vulnerabilities': vulns
            })
        
        return {'categories': categories}
    
    def is_valid_vulnerability(self, vulnerability_name: str) -> bool:
        """检查漏洞名称是否有效（从 vulnerability_db.json）"""
        vulnerabilities = self._vulnerability_db.get("vulnerabilities", {})
        return vulnerability_name in vulnerabilities
    
    def get_category_for_vulnerability(self, vulnerability_name: str) -> str:
        """获取漏洞所属的一级分类（从 vulnerability_db.json）"""
        vulnerabilities = self._vulnerability_db.get("vulnerabilities", {})
        if vulnerability_name in vulnerabilities:
            return vulnerabilities[vulnerability_name].get("category", "")
        return ""
    
# 创建全局实例（单例模式）
_config_loader = None


def get_config_loader() -> ConfigLoader:
    """获取配置加载器实例（单例模式）"""
    global _config_loader
    
    if _config_loader is None:
        _config_loader = ConfigLoader()
    
    return _config_loader

