"""核心引擎模块"""

import os
import json
from typing import Dict, Any, Optional, Union, Tuple
from hos_m2f.converters import get_converter
from hos_m2f.parsers import get_parser
from hos_m2f.resources.resource_manager import ResourceManager


class Engine:
    """核心引擎类，负责处理文档转换和构建"""
    
    def __init__(self):
        """初始化引擎"""
        self.resource_manager = ResourceManager()
        self.supported_modes = {
            "paper": "学术论文模式",
            "patent": "专利申请模式",
            "book": "书籍模式",
            "sop": "标准操作流程模式"
        }
        self.supported_formats = {
            "md": "Markdown",
            "markdown": "Markdown",
            "docx": "Microsoft Word",
            "json": "JSON",
            "epub": " EPUB电子书",
            "html": "HTML",
            "xml": "XML",
            "pdf": "PDF",
            "xlsx": "Excel"
        }
    
    def build(self, content: str, mode: str, format: str, options: Dict[str, Any] = None) -> Dict[str, Any]:
        """构建文档
        
        Args:
            content: 输入内容
            mode: 文档模式
            format: 输出格式
            options: 额外选项
            
        Returns:
            构建结果
        """
        if options is None:
            options = {}
        
        # 解析内容
        parser = get_parser("md")
        parsed_content = parser.parse(content, options)
        
        # 转换为目标格式
        converter = get_converter("md", format)
        result = converter.convert(content, options)
        
        return {
            "binary": result,
            "output_format": format,
            "metadata": {
                "mode": mode,
                "format": format,
                "options": options
            }
        }
    
    def check(self, content: str, mode: str, options: Dict[str, Any] = None) -> Dict[str, Any]:
        """检查文档
        
        Args:
            content: 输入内容
            mode: 文档模式
            options: 额外选项
            
        Returns:
            检查结果
        """
        if options is None:
            options = {}
        
        # 简单的检查实现
        issues = []
        
        # 检查内容长度
        if len(content) < 10:
            issues.append("内容过短")
        
        # 检查模式是否支持
        if mode not in self.supported_modes:
            issues.append(f"不支持的模式: {mode}")
        
        return {
            "compliance": {
                "compliant": len(issues) == 0,
                "issues": issues
            },
            "metadata": {
                "mode": mode,
                "content_length": len(content)
            }
        }
    
    def convert(self, input_path: str, output_path: str, from_format: str, to_format: str, options: Dict[str, Any] = None) -> Dict[str, Any]:
        """转换文件格式
        
        Args:
            input_path: 输入文件路径
            output_path: 输出文件路径
            from_format: 输入格式
            to_format: 输出格式
            options: 额外选项
            
        Returns:
            转换结果
        """
        if options is None:
            options = {}
        
        # 读取输入文件
        with open(input_path, 'rb') as f:
            input_content = f.read()
        
        # 执行转换
        output_content = self.convert_content(from_format, to_format, input_content, options)
        
        # 写入输出文件
        with open(output_path, 'wb') as f:
            f.write(output_content)
        
        return {
            "success": True,
            "input_path": input_path,
            "output_path": output_path,
            "from_format": from_format,
            "to_format": to_format,
            "metadata": {
                "input_size": len(input_content),
                "output_size": len(output_content),
                "options": options
            }
        }
    
    def convert_content(self, input_format: str, output_format: str, input_content: bytes, options: Dict[str, Any] = None) -> bytes:
        """转换内容格式
        
        Args:
            input_format: 输入格式
            output_format: 输出格式
            input_content: 输入内容的二进制数据
            options: 额外选项
            
        Returns:
            输出内容的二进制数据
        """
        if options is None:
            options = {}
        
        # 获取转换器
        converter = get_converter(input_format, output_format)
        
        # 执行转换
        output_content = converter.convert(input_content, options)
        
        return output_content
    
    def get_supported_modes(self) -> Dict[str, str]:
        """获取支持的模式
        
        Returns:
            支持的模式字典
        """
        return self.supported_modes
    
    def get_supported_formats(self) -> Dict[str, str]:
        """获取支持的格式
        
        Returns:
            支持的格式字典
        """
        return self.supported_formats
    
    def run_ai_pipeline(self, docx_path: str, ai_content: str, ai_instructions: str, output_dir: Optional[str] = None) -> Dict[str, Any]:
        """运行完整的AI文档自动化流水线
        
        Args:
            docx_path: DOCX文件路径
            ai_content: AI生成的内容
            ai_instructions: AI指令
            output_dir: 输出目录
            
        Returns:
            流水线运行结果
        """
        from hos_m2f.pipeline import PipelineCoordinator
        
        # 初始化流水线协调器
        coordinator = PipelineCoordinator()
        
        # 运行完整流水线
        result = coordinator.full_pipeline(
            docx_path,
            ai_content,
            ai_instructions,
            output_dir=output_dir
        )
        
        return result
    
    def get_ai_pipeline_component(self, component_name: str) -> Any:
        """获取AI流水线的单个组件
        
        Args:
            component_name: 组件名称
            
        Returns:
            对应的AI流水线组件
        """
        from hos_m2f.pipeline import (
            XMLTemplater,
            MarkdownConverter,
            TemplateRenderer,
            XMLModifier,
            SchemaGenerator,
            AIPromptManager,
            LogManager,
            PipelineCoordinator
        )
        
        component_map = {
            'xml_templater': XMLTemplater,
            'markdown_converter': MarkdownConverter,
            'template_renderer': TemplateRenderer,
            'xml_modifier': XMLModifier,
            'schema_generator': SchemaGenerator,
            'ai_prompt_manager': AIPromptManager,
            'log_manager': LogManager,
            'pipeline_coordinator': PipelineCoordinator
        }
        
        component_class = component_map.get(component_name.lower())
        if not component_class:
            raise ValueError(f"Unknown component: {component_name}")
        
        return component_class()
    
    def generate_ai_prompt(self, task_type: str, **kwargs) -> str:
        """生成AI提示词
        
        Args:
            task_type: 任务类型
            **kwargs: 额外参数
            
        Returns:
            AI提示词
        """
        manager = self.get_ai_pipeline_component('ai_prompt_manager')
        
        if task_type == 'content_generation':
            schema = kwargs.get('schema')
            context = kwargs.get('context')
            return manager.get_content_generation_prompt(schema=schema, context=context)
        elif task_type == 'xml_modification':
            context = kwargs.get('context')
            return manager.get_xml_modification_prompt(context=context)
        else:
            raise ValueError(f"Unknown task type: {task_type}")
    
    def generate_schema(self, xml_content: str, format: str = 'json_schema') -> Any:
        """从XML生成Schema
        
        Args:
            xml_content: XML内容
            format: Schema格式
            
        Returns:
            生成的Schema
        """
        generator = self.get_ai_pipeline_component('schema_generator')
        return generator.generate_from_xml(xml_content, format=format)
    
    def generate_xml_template(self, xml_content: str) -> Tuple[str, Dict[str, str]]:
        """生成XML模板
        
        Args:
            xml_content: XML内容
            
        Returns:
            (模板XML, 变量映射表)
        """
        templater = self.get_ai_pipeline_component('xml_templater')
        return templater.template_auto(xml_content)
