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

import asyncio
from typing import Optional, Callable
from datetime import datetime

from foundation.logger.loggering import server_logger as logger
from ..component import DocumentProcessor

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

    def __init__(self, file_id: str, callback_task_id: str, user_id: str,
                 progress_manager=None, redis_duplicate_checker=None):
        self.file_id = file_id
        self.callback_task_id = callback_task_id
        self.user_id = user_id
        self.progress_manager = progress_manager
        self.redis_duplicate_checker = redis_duplicate_checker
        self.document_processor = DocumentProcessor()

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

            # 检查是否已初始化进度，避免重复初始化
            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=100,
                status="docu_ans_completed",
                message="开始文档解析"
            )

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

            result = {
                'file_id': self.file_id,
                'structured_content': structured_content,
                'document_name': structured_content['document_name'],
                'total_chunks': structured_content['total_chunks'],
                'metadata': structured_content['metadata']
            }

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

        except Exception as e:
            logger.error(f"文档处理工作流失败: {str(e)}")

            # 更新错误状态
            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)}"
                )

            raise

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