"""
文档处理工作流
负责文档处理的流程控制和业务编排
"""

import asyncio

from foundation.observability.logger.loggering import review_logger as logger
from ..component.document_processor import DocumentProcessor
from core.base.task_models import TaskFileInfo

class DocumentWorkflow:
    """文档处理工作流"""

    def __init__(self, task_file_info: TaskFileInfo = None, file_id: str = None, callback_task_id: str = None,
                 user_id: str = None, progress_manager=None, redis_duplicate_checker=None):
        """
        初始化文档处理工作流

        Args:
            task_file_info: TaskFileInfo 实例（推荐方式）
            file_id: 文件ID（兼容旧接口）
            callback_task_id: 回调任务ID（兼容旧接口）
            user_id: 用户ID（兼容旧接口）
        """

        self.task_info = task_file_info
        self.file_id = task_file_info.file_id
        self.callback_task_id = task_file_info.callback_task_id
        self.user_id = task_file_info.user_id


        self.progress_manager = progress_manager
        self.redis_duplicate_checker = redis_duplicate_checker
        # 从配置读取是否启用 OCR
        from foundation.infrastructure.config.config import config_handler
        use_ocr_str = config_handler.get("ocr", "enable", "false")
        use_ocr = use_ocr_str.lower() in ("true", "1", "yes", "on")

        self.document_processor = DocumentProcessor(
            progress_manager=progress_manager,
            callback_task_id=task_file_info.callback_task_id,
            use_ocr=use_ocr
        )

    async def _processing_heartbeat(self, progress_state: dict) -> None:
        """
        文档处理期间每 10 秒向前端推送一次进度提醒，直到被取消。
        从 progress_state 读取 hybrid_extractor 实时更新的页级进度。
        """
        while True:
            await asyncio.sleep(10)
            try:
                current = progress_state.get('current', 0)
                message = progress_state.get('message', 'OCR识别中，请耐心等待...')
                stage = progress_state.get('stage', '文档解析')
                await self.progress_manager.update_stage_progress(
                    callback_task_id=self.callback_task_id,
                    stage_name=stage,
                    current=current,
                    status="processing",
                    message=message,
                    event_type="processing"
                )
                logger.debug(f"文档解析心跳推送 stage={stage} current={current}，任务ID: {self.callback_task_id}")
            except asyncio.CancelledError:
                raise
            except Exception as e:
                logger.warning(f"文档解析心跳推送失败: {e}")

    async def execute(self, file_content: bytes, file_type: str) -> dict:
        """执行文档处理工作流"""
        heartbeat_task = None
        try:
            logger.info(f"开始文档处理工作流，文件ID: {self.file_id}")

            # 共享进度状态：由 hybrid_extractor（线程）和 document_processor（异步）写入，心跳协程读取
            # stage 字段决定心跳推送时使用的 stage_name，随处理阶段切换
            progress_state = {'current': 0, 'message': '版面分析中...', 'stage': '文档解析'}

            # 将进度状态同时注入到：
            # 1. HybridFullTextExtractor（OCR线程中更新）
            # 2. DocumentProcessor（分类阶段异步更新）
            try:
                from ..component.doc_worker.pdf_worker.hybrid_extractor import HybridFullTextExtractor
                pdf_extractor = self.document_processor._components.get('pdf')
                if pdf_extractor is not None:
                    extractor = getattr(pdf_extractor, 'fulltext_extractor', None)
                    if isinstance(extractor, HybridFullTextExtractor):
                        extractor._progress_state = progress_state
                        logger.debug("已将进度状态注入到 HybridFullTextExtractor")
                self.document_processor._progress_state = progress_state
                logger.debug("已将进度状态注入到 DocumentProcessor")
            except Exception as e:
                logger.warning(f"注入进度状态失败，将使用固定提示: {e}")

            # 检查是否已初始化进度，避免重复初始化
            if self.progress_manager:
                existing_progress = await self.progress_manager.get_progress(self.callback_task_id)
                if not existing_progress:
                    logger.warning(f"文档处理工作流未找到进度数据: {self.callback_task_id}")

                await self.progress_manager.update_stage_progress(
                    callback_task_id=self.callback_task_id,
                    stage_name="文档解析",
                    current=0,
                    status="processing",
                    message="开始文档解析...",
                    event_type="processing"
                )

                # 启动心跳任务：每 10 秒从 progress_state 读取真实进度推送
                heartbeat_task = asyncio.create_task(self._processing_heartbeat(progress_state))

            structured_content = await self.document_processor.process_document(
                file_content=file_content,
                file_type=file_type,
            )

            # 处理完成，取消心跳
            if heartbeat_task:
                heartbeat_task.cancel()
                try:
                    await heartbeat_task
                except asyncio.CancelledError:
                    pass

            if self.progress_manager:
                await self.progress_manager.update_stage_progress(
                    callback_task_id=self.callback_task_id,
                    stage_name="文档解析",
                    current=100,
                    status="docu_ans_completed",
                    message="文档解析完成",
                    event_type="processing"
                )

            # 转换为旧版字典格式以保持兼容性
            structured_content_legacy = structured_content.to_legacy_dict()

            result = {
                'file_id': self.file_id,
                'structured_content': structured_content_legacy,
                'document_name': structured_content.document_name,
                'total_chunks': structured_content.secondary_count,
                'metadata': {
                    'total_pages': structured_content.total_pages,
                    'total_lines': structured_content.total_lines,
                    'primary_count': structured_content.primary_count,
                    'secondary_count': structured_content.secondary_count,
                    'tertiary_count': structured_content.tertiary_count,
                    'processing_timestamp': structured_content.processing_timestamp,
                    'raw_metadata': structured_content.raw_metadata,
                }
            }

            logger.info(f"文档处理工作流完成，文件ID: {self.file_id}")
            return result

        except Exception as e:
            # 异常时同样取消心跳
            if heartbeat_task:
                heartbeat_task.cancel()
                try:
                    await heartbeat_task
                except asyncio.CancelledError:
                    pass

            logger.error(f"文档处理工作流失败: {str(e)}", exc_info=True)

            # 更新错误状态
            if self.progress_manager:
                await self.progress_manager.update_stage_progress(
                    callback_task_id=self.callback_task_id,
                    stage_name="文档解析",
                    current=0,
                    status="failed",
                    message=f"处理失败: {str(e)}",
                    event_type="error"
                )

            raise

    async def get_status(self) -> dict:
        """获取工作流状态"""
        if self.progress_manager:
            return await self.progress_manager.get_progress(self.callback_task_id)
        return {}