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

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

from foundation.observability.logger.loggering import review_logger as logger
from ..component.report_generator import ReportGenerator

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

    def __init__(self, file_id: str, file_name: str, callback_task_id: str, user_id: str,
                 ai_review_results: dict, progress_manager=None):
        """
        初始化报告生成工作流

        Args:
            file_id: 文件ID
            file_name: 文件名称
            callback_task_id: 回调任务ID
            user_id: 用户ID
            ai_review_results: AI审查结果（包含issues列表）
            progress_manager: 进度管理器
        """
        self.file_id = file_id
        self.file_name = file_name
        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:
        """
        执行报告生成工作流

        Returns:
            dict: 报告生成结果
        """
        try:
            logger.info(f"开始报告生成工作流，文件ID: {self.file_id}, 文件名: {self.file_name}")

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

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

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

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

            # 4. 转换为字典格式返回
            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)}", exc_info=True)

            # 更新错误状态（标记为完成，但使用降级报告）
            if self.progress_manager:
                await self.progress_manager.update_stage_progress(
                    callback_task_id=self.callback_task_id,
                    stage_name="报告生成",
                    current=95,
                    status="completed",
                    message=f"报告生成使用了降级方案（LLM服务暂时不可用）"
                )

            # 返回降级报告，不让任务完全失败
            fallback_report = self._generate_fallback_report()
            logger.warning(f"返回降级报告，文件ID: {self.file_id}")
            return fallback_report

    def _generate_fallback_report(self) -> dict:
        """
        生成降级报告（当 LLM 报告生成失败时使用）
        
        Returns:
            dict: 降级报告字典
        """
        
        # 从 AI 审查结果中提取问题统计
        review_results = self.ai_review_results.get('review_results', [])
        high_count = 0
        medium_count = 0
        low_count = 0
        
        for issue_wrapper in review_results:
            for issue_id, issue_detail in issue_wrapper.items():
                review_lists = issue_detail.get('review_lists', [])
                for review_item in review_lists:
                    if not review_item.get('exist_issue', False):
                        continue
                    check_result = review_item.get('check_result', {})
                    if isinstance(check_result, str):
                        continue
                    risk_level = check_result.get('risk_level', '').lower()
                    if '高' in risk_level or 'high' in risk_level:
                        high_count += 1
                    elif '中' in risk_level or 'medium' in risk_level:
                        medium_count += 1
                    else:
                        low_count += 1
        
        total_issues = high_count + medium_count + low_count
        
        return {
            'file_id': self.file_id,
            'file_name': self.file_name,
            'total_issues': total_issues,
            'risk_stats': {
                'high': high_count,
                'medium': medium_count,
                'low': low_count
            },
            'overall_assessment': f"【降级报告】文档《{self.file_name}》的审查已完成。共发现 {total_issues} 个问题，其中高风险 {high_count} 个，中风险 {medium_count} 个，低风险 {low_count} 个。（注：由于 LLM 服务暂时不可用，此报告为自动生成的简要统计）",
            'high_risk_summary': ["请查看详细审查结果了解高风险问题"] if high_count > 0 else ["未发现高风险问题"],
            'medium_risk_summary': ["请查看详细审查结果了解中风险问题"] if medium_count > 0 else ["未发现中风险问题"],
            'improvement_recommendations': [
                f"优先处理 {high_count} 个高风险问题" if high_count > 0 else "文档整体质量良好",
                f"建议处理 {medium_count} 个中风险问题" if medium_count > 0 else None,
                "【系统提示】报告摘要生成服务暂时不可用，以上为自动生成的简要统计"
            ],
            'risk_alerts': [
                f"⚠️ 发现 {high_count} 个高风险问题，需要关注" if high_count > 0 else None,
                f"⚠️ 发现 {medium_count} 个中风险问题" if medium_count > 0 else None
            ],
            'generated_at': datetime.now().isoformat(),
            'is_fallback': True  # 标记为降级报告
        }

    def _convert_report_to_dict(self, final_report) -> dict:
        """
        将报告对象转换为字典

        Args:
            final_report: FinalReport对象

        Returns:
            dict: 报告字典
        """
        return {
            'file_id': final_report.file_id,
            'file_name': final_report.file_name,
            'total_issues': final_report.total_issues,
            'risk_stats': {
                'high': final_report.high_risk_count,
                'medium': final_report.medium_risk_count,
                'low': final_report.low_risk_count
            },
            'overall_assessment': final_report.overall_assessment,
            'high_risk_summary': final_report.high_risk_summary,
            'medium_risk_summary': final_report.medium_risk_summary,
            'improvement_recommendations': final_report.improvement_recommendations,
            'risk_alerts': final_report.risk_alerts,
            '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 {}