#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Document Processor
统一文档处理器 - 集成文本提取、内容整合和格式转换功能
"""

import logging
from typing import List, Dict, Any, Optional, Union
from pathlib import Path

from .text_extractor import TextExtractor, ExtractedDocument
from .content_integrator import ContentIntegrator, IntegratedContent
from .content_transformer import ContentTransformer, TransformedContent
from ..config import AlgorithmConfig
from ..exceptions import DocumentProcessingError

logger = logging.getLogger(__name__)


class DocumentProcessor:
    """
    统一文档处理器
    提供完整的文档处理流水线：提取 -> 整合 -> 转换
    """
    
    def __init__(self, config: AlgorithmConfig):
        """
        初始化文档处理器
        
        Args:
            config: 算法配置
        """
        self.config = config
        self.text_extractor = TextExtractor(config.document_processing)
        self.content_integrator = ContentIntegrator(config.document_processing)
        self.content_transformer = ContentTransformer(config)
        
        logger.info("统一文档处理器初始化完成")
    
    async def process_documents(
        self,
        sources: Union[str, Path, List[Union[str, Path]]],
        target_format: str = 'summary',
        custom_prompt: Optional[str] = None,
        additional_requirements: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        完整的文档处理流水线
        
        Args:
            sources: 文档源（文件路径、目录路径或路径列表）
            target_format: 目标转换格式
            custom_prompt: 自定义提示词
            additional_requirements: 额外要求
            
        Returns:
            包含所有处理结果的字典
        """
        try:
            logger.info(f"开始文档处理流水线，目标格式: {target_format}")
            
            # 第一步：提取文档内容
            extracted_docs = self._extract_documents(sources)
            
            if not extracted_docs:
                raise DocumentProcessingError("没有成功提取的文档")
            
            # 第二步：整合文档内容
            integrated_content = self.content_integrator.integrate_documents(extracted_docs)
            
            # 第三步：转换为目标格式
            transformed_content = await self.content_transformer.transform_content(
                integrated_content=integrated_content,
                format_type=target_format,
                custom_prompt=custom_prompt,
                additional_requirements=additional_requirements
            )
            
            # 整理最终结果
            result = {
                'processing_summary': {
                    'total_documents': len(extracted_docs),
                    'successful_extractions': len([d for d in extracted_docs if not d.error_info]),
                    'target_format': target_format,
                    'processing_completed': True
                },
                'extracted_documents': [doc.get_summary() for doc in extracted_docs],
                'integrated_content': integrated_content.to_dict(),
                'transformed_content': transformed_content.to_dict(),
                'final_output': transformed_content.transformed_text,
                'quality_metrics': {
                    'extraction_success_rate': len([d for d in extracted_docs if not d.error_info]) / len(extracted_docs),
                    'content_integration_quality': len(integrated_content.key_topics) / max(1, integrated_content.document_count),
                    'transformation_quality': transformed_content.quality_score
                }
            }
            
            logger.info(f"文档处理流水线完成，最终输出长度: {len(transformed_content.transformed_text)}")
            return result
            
        except Exception as e:
            error_msg = f"文档处理流水线失败: {str(e)}"
            logger.error(error_msg, exc_info=True)
            raise DocumentProcessingError(error_msg)
    
    def _extract_documents(self, sources: Union[str, Path, List[Union[str, Path]]]) -> List[ExtractedDocument]:
        """提取文档内容"""
        if isinstance(sources, (str, Path)):
            sources = [sources]
        
        extracted_docs = []
        
        for source in sources:
            source_path = Path(source)
            
            try:
                if source_path.is_file():
                    # 处理单个文件
                    doc = self.text_extractor.extract_from_file(source_path)
                    extracted_docs.append(doc)
                elif source_path.is_dir():
                    # 处理目录中的所有文件
                    dir_docs = self.text_extractor.extract_from_directory(source_path)
                    extracted_docs.extend(dir_docs)
                else:
                    logger.warning(f"无效的文档源: {source_path}")
                    
            except Exception as e:
                logger.error(f"处理文档源失败 {source_path}: {e}")
                continue
        
        return extracted_docs
    
    async def extract_only(
        self, 
        sources: Union[str, Path, List[Union[str, Path]]]
    ) -> List[ExtractedDocument]:
        """仅执行文档提取"""
        return self._extract_documents(sources)
    
    def integrate_only(self, documents: List[ExtractedDocument]) -> IntegratedContent:
        """仅执行内容整合"""
        return self.content_integrator.integrate_documents(documents)
    
    async def transform_only(
        self,
        integrated_content: IntegratedContent,
        target_format: str = 'summary',
        custom_prompt: Optional[str] = None,
        additional_requirements: Optional[str] = None
    ) -> TransformedContent:
        """仅执行内容转换"""
        return await self.content_transformer.transform_content(
            integrated_content=integrated_content,
            format_type=target_format,
            custom_prompt=custom_prompt,
            additional_requirements=additional_requirements
        )
    
    def get_supported_formats(self) -> Dict[str, str]:
        """获取支持的文件格式和转换格式"""
        return {
            'input_formats': self.text_extractor.get_supported_formats(),
            'output_formats': self.content_transformer.get_supported_formats()
        }
    
    def get_processing_stats(self) -> Dict[str, Any]:
        """获取处理器统计信息"""
        return {
            'extractor_stats': self.text_extractor.get_extraction_stats(),
            'integrator_stats': self.content_integrator.get_integration_stats(),
            'transformer_stats': self.content_transformer.get_transformation_stats(),
            'supported_formats': self.get_supported_formats()
        }
    
    async def batch_process_directories(
        self,
        directories: List[Union[str, Path]],
        target_format: str = 'summary'
    ) -> Dict[str, Dict[str, Any]]:
        """批量处理多个目录"""
        results = {}
        
        for i, directory in enumerate(directories):
            try:
                logger.info(f"批量处理目录 {i+1}/{len(directories)}: {directory}")
                
                result = await self.process_documents(
                    sources=directory,
                    target_format=target_format
                )
                
                results[str(directory)] = result
                
            except Exception as e:
                logger.error(f"批量处理目录失败 {directory}: {e}")
                results[str(directory)] = {'error': str(e)}
        
        return results 