"""模型工厂 - 根据配置创建模型实例"""
from typing import Dict, Any, Optional
from models.adapters import BasePreprocessor, BaseLayoutDetector, BaseVLRecognizer, BaseOCRRecognizer

class ModelFactory:
    """模型工厂类，负责创建和管理各种模型适配器"""
    
    _adapters_registry = {}
    
    @classmethod
    def register_adapter(cls, adapter_type: str, module_name: str, class_name: str):
        """注册适配器"""
        cls._adapters_registry[adapter_type] = {
            'module': module_name,
            'class': class_name
        }
    
    @classmethod
    def create_preprocessor(cls, config: Dict[str, Any]) -> BasePreprocessor:
        """创建预处理器"""
        module_name = config.get('module', 'mineru')
        
        if module_name == 'mineru':
            from models.adapters import MinerUPreprocessor
            preprocessor = MinerUPreprocessor(config)
        else:
            raise ValueError(f"Unknown preprocessor module: {module_name}")
            
        preprocessor.initialize()
        return preprocessor
    
    @classmethod
    def create_layout_detector(cls, config: Dict[str, Any]) -> BaseLayoutDetector:
        # 根据配置创建检测器
        module_name = config.get('module', 'mineru')
        if module_name == 'paddle':
            from models.adapters import PaddleLayoutDetector
            detector = PaddleLayoutDetector(config)
        elif module_name == 'docling':
            from models.adapters import DoclingLayoutDetector
            detector = DoclingLayoutDetector(config)
        elif module_name == 'mineru':
            from models.adapters import MinerULayoutDetector
            detector = MinerULayoutDetector(config)
        else:
            raise ValueError(f"Unknown layout detector module: {module_name}")
        try:
            detector.initialize()
            return detector
        except Exception as e:
            print(f"Failed to initialize layout detector: {e}")
            raise
    
    @classmethod
    def create_vl_recognizer(cls, config: Dict[str, Any]) -> BaseVLRecognizer:
        """创建VL识别器"""
        module_name = config.get('module', 'mineru')
        
        if module_name == 'paddle':
            from models.adapters import PaddleVLRecognizer
            recognizer = PaddleVLRecognizer(config)
        elif module_name == 'mineru':
            from models.adapters import MinerUVLRecognizer
            recognizer = MinerUVLRecognizer(config)
        else:
            raise ValueError(f"Unknown VL recognizer module: {module_name}")
            
        recognizer.initialize()
        return recognizer
    
    @classmethod
    def create_ocr_recognizer(cls, config: Dict[str, Any]) -> BaseOCRRecognizer:
        """创建OCR识别器"""
        module_name = config.get('module', 'mineru')
        
        if module_name == 'mineru':
            from models.adapters import MinerUOCRRecognizer
            recognizer = MinerUOCRRecognizer(config)
        else:
            raise ValueError(f"Unknown OCR recognizer module: {module_name}")
            
        recognizer.initialize()
        return recognizer
    
    @classmethod
    def cleanup_all(cls):
        """清理所有模型资源"""
        # 在实际应用中，可以维护一个活跃模型列表进行清理
        pass

# 注册默认适配器
ModelFactory.register_adapter('preprocessor', 'mineru_adapter', 'MinerUPreprocessor')
ModelFactory.register_adapter('layout_detector', 'mineru_adapter', 'MinerULayoutDetector')
ModelFactory.register_adapter('vl_recognizer', 'mineru_adapter', 'MinerUVLRecognizer')
ModelFactory.register_adapter('ocr_recognizer', 'mineru_adapter', 'MinerUOCRRecognizer')

ModelFactory.register_adapter('layout_detector', 'paddle_adapter', 'PaddleLayoutDetector')
ModelFactory.register_adapter('layout_detector', 'docling_adapter', 'DoclingLayoutDetector')