"""
报告生成工作流
负责报告生成的流程控制和业务编排
"""

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

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

class ReportWorkflow:
    """报告生成工作流"""

    def __init__(self, file_id: str, callback_task_id: str, user_id: str,
                 ai_review_results: dict, progress_manager=None):
        self.file_id = file_id
        self.callback_task_id = callback_task_id
        self.user_id = user_id
        self.ai_review_results = ai_review_results
        self.progress_manager = progress_manager
        self.report_generator = ReportGenerator()

    async def execute(self) -> dict:
        """执行报告生成工作流"""
        try:
            logger.info(f"开始报告生成工作流，文件ID: {self.file_id}")

            # 1. 初始化进度
            await self.progress_manager.update_stage_progress(
                callback_task_id=self.callback_task_id,
                stage_name="报告生成",
                progress=0,
                status="processing",
                message="开始生成报告"
            )

            # 2. 生成报告
            def progress_callback(progress: int, message: str):
                # 将报告生成的进度映射到整体进度
                overall_progress = 90 + int(progress * 0.1)  # 报告生成占整体进度的10%
                asyncio.create_task(
                    self.progress_manager.update_stage_progress(
                        callback_task_id=self.callback_task_id,
                        stage_name="报告生成",
                        progress=overall_progress,
                        status="processing",
                        message=message
                    )
                )

            final_report = await self.report_generator.generate_report(
                file_id=self.file_id,
                review_results=self.ai_review_results,
                progress_callback=progress_callback
            )

            # 3. 更新完成状态
            await self.progress_manager.update_stage_progress(
                callback_task_id=self.callback_task_id,
                stage_name="报告生成",
                progress=100,
                status="completed",
                message="报告生成完成"
            )

            # 4. 标记任务链完成
            await self.progress_manager.complete_task(
                callback_task_id=self.callback_task_id,
                result=self._convert_report_to_dict(final_report)
            )

            # 5. 处理结果
            result = self._convert_report_to_dict(final_report)

            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="报告生成",
                    progress=90,
                    status="failed",
                    message=f"报告生成失败: {str(e)}"
                )

            raise

    def _convert_report_to_dict(self, final_report) -> dict:
        """将报告对象转换为字典"""
        return {
            'file_id': final_report.file_id,
            'document_name': final_report.document_name,
            'risk_stats': final_report.risk_stats,
            'dimension_scores': {
                'safety': final_report.dimension_scores.safety,
                'quality': final_report.dimension_scores.quality,
                'schedule': final_report.dimension_scores.schedule,
                'cost': final_report.dimension_scores.cost
            },
            'summary_report': final_report.summary_report,
            'multidimensional_report': final_report.multidimensional_report,
            'recommendations': final_report.recommendations,
            'generated_at': final_report.generated_at.isoformat()
        }

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