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

"""
@Project   : lq-agent-api
@File      : ai_review_engine.py
@IDE       : VsCode
@Author    : 王旭明
@Date      : 2025-12-01 11:07:12
@Description: AI审查引擎核心组件，负责执行各类文档审查任务，支持并发处理和多种审查模式

=================================
📋 方法总览 (Method Overview)
=================================

🏗️ 核心审查流程:
├── basic_compliance_check()      # 基础合规性检查 (语法/语义/完整性)
├── technical_compliance_check()  # 技术性合规检查 (标准/设计/参数)
├── rag_enhanced_check()          # RAG增强审查 (向量/混合检索)
└── _calculate_overall_risk()     # 计算总体风险等级

🔍 专项检查方法:
├── check_grammar()               # 词句语法检查
├── check_semantic_logic()        # 语义逻辑检查
├── check_completeness()          # 完整性检查
├── check_mandatory_standards()   # 强制性标准检查
├── check_design_values()         # 设计值检查
└── check_technical_parameters()  # 技术参数检查

🔍 RAG检索增强:
├── vector_search()               # 向量检索
├── hybrid_search()               # 混合检索
├── rerank_results()              # 重排序结果
└── generate_enhanced_suggestions() # 生成增强建议

🛠️ 工具辅助方法:
├── _process_review_result()      # 处理审查结果
├── _execute_check_with_semaphore() # 信号量并发控制
├── _calculate_basic_score()      # 计算基础得分
├── _calculate_technical_score()  # 计算技术得分
└── _aggregate_results()          # 汇总审查结果

⚙️ 配置管理:
├── __init__()                    # 初始化引擎 (max_concurrent_reviews=8)
└── set_review_location_label()   # 设置审查位置标签
"""

import time
import asyncio
from enum import Enum
from dataclasses import dataclass
from typing import Dict, List, Any
from foundation.logger.loggering import server_logger as logger
from core.construction_review.component.reviewers.base_reviewer import BaseReviewer,BaseRAGReviewer
@dataclass
class ReviewResult:
    """审查结果"""
    unit_index: int
    unit_content: Dict[str, Any]
    basic_compliance: Dict[str, Any]
    technical_compliance: Dict[str, Any]
    rag_enhanced: Dict[str, Any]
    overall_risk: str

class Stage(Enum):
    """工作流状态"""
    BASIC = {
        'reviewer_type':'basic',
        'sensitive': 'sensitive_word_check',
        'semantic': 'semantic_logic_check',
        'completeness': 'completeness_check',
        'timeliness': 'timeliness_check',
        'reference': 'reference_check'
    }
    TECHNICAL = {
        'reviewer_type':'technical',
        'mandatory': 'mandatory_standards_check',
        'technical': 'technical_parameters_check',
        'design': 'design_values_check'
    }
    RAG = {
        'reviewer_type':'rag',
        'rag': 'rag_enhanced_review',
        'vector': 'vector_search_review',
        'hybrid': 'hybrid_search_review'
    }
    AI = {
        'reviewer_type':'ai',
        'professional': 'professional_suggestion',
        'standardization': 'standardization_suggestion',
        'completeness': 'completeness_suggestion',
        'readability': 'readability_suggestion'
    }


class AIReviewEngine(BaseReviewer):
    """AI审查引擎 - 支持审查条目并发"""

    def __init__(self, max_concurrent_reviews: int = 8):
        super().__init__()
        self.max_concurrent_reviews = max_concurrent_reviews
        self.semaphore = asyncio.Semaphore(max_concurrent_reviews)

    def set_review_location_label(self, location_label: str):
        """
        设置审查位置标签

        Args:
            location_label: 位置标签字符串
        """
        self.review_location_label = location_label

    def _process_review_result(self, result):
        """
        处理审查结果，统一转换为字典格式

        Args:
            result: 原始审查结果

        Returns:
            Dict: 处理后的审查结果字典
        """
        if isinstance(result, Exception):
            return {"error": str(result), "success": False}
        elif hasattr(result, '__dict__'):  # ReviewResult对象
            return {
                "success": result.success if hasattr(result, 'success') else False,
                "details": result.details if hasattr(result, 'details') else {},
                "error_message": result.error_message if hasattr(result, 'error_message') else None,
                "execution_time": result.execution_time if hasattr(result, 'execution_time') else None
            }
        else:
            return result  # 已经是字典

    def _execute_check_with_semaphore(self, check_func, *args, **kwargs):
        """
        使用信号量执行检查任务的包装器

        Args:
            check_func: 检查函数
            *args: 位置参数
            **kwargs: 关键字参数

        Returns:
            包装后的异步函数
        """
        async def wrapped_check():
            async with self.semaphore:
                return await check_func(*args, **kwargs)
        return wrapped_check()

    async def basic_compliance_check(self, trace_id_idx: str, unit_content: Dict[str, Any],
                                   stage_name: str = None, state: dict = None, current_progress: int = None) -> Dict[str, Any]:
        """
        基础合规性检查

        Args:
            trace_id_idx: 追踪ID索引
            unit_content: 待审查单元内容
            stage_name: 阶段名称
            state: 状态字典
            current_progress: 当前进度

        Returns:
            Dict[str, Any]: 基础合规性检查结果
        """
        review_content = unit_content['content']
        review_references = unit_content.get('review_references')

        logger.info(f"开始基础合规性检查, 内容长度: {len(review_content)}")

        async def check_with_semaphore(check_func, *args):
            async with self.semaphore:
                return await check_func(*args, stage_name=stage_name, state=state, current_progress=current_progress)

        basic_tasks = [
            check_with_semaphore(self.check_grammar, trace_id_idx, review_content, review_references),
            check_with_semaphore(self.check_semantic_logic, trace_id_idx, review_content, review_references),
            check_with_semaphore(self.check_completeness, trace_id_idx, review_content, review_references)
        ]


        grammar_result, semantic_result, completeness_result = await asyncio.gather(*basic_tasks, return_exceptions=True)

        # 使用公共方法处理结果
        grammar_result = self._process_review_result(grammar_result)
        semantic_result = self._process_review_result(semantic_result)
        completeness_result = self._process_review_result(completeness_result)

        return {
            'grammar_check': grammar_result,
            'semantic_check': semantic_result,
            'completeness_check': completeness_result,
            'overall_score': self._calculate_basic_score(grammar_result, semantic_result, completeness_result)
        }

    async def technical_compliance_check(self, trace_id_idx: str, unit_content: Dict[str, Any],
                                      stage_name: str = None, state: dict = None, current_progress: int = None) -> Dict[str, Any]:
        """
        技术性合规检查

        Args:
            trace_id_idx: 追踪ID索引
            unit_content: 待审查单元内容
            stage_name: 阶段名称
            state: 状态字典
            current_progress: 当前进度

        Returns:
            Dict[str, Any]: 技术性合规检查结果
        """
        review_content = unit_content['content']
        review_references = unit_content.get('review_references')
        logger.info(f"开始技术性合规检查，内容长度: {len(review_content)}")
        async def check_with_semaphore(check_func, *args):
            async with self.semaphore:
                return await check_func(*args, stage_name=stage_name, state=state, current_progress=current_progress)

        technical_tasks = [
            check_with_semaphore(self.check_mandatory_standards, trace_id_idx, review_content,review_references),
            check_with_semaphore(self.check_design_values, trace_id_idx, review_content,review_references),
            check_with_semaphore(self.check_technical_parameters, trace_id_idx, review_content,review_references)
        ]

        mandatory_result, design_value_result, technical_param_result = await asyncio.gather(*technical_tasks, return_exceptions=True)

        # 使用公共方法处理结果
        mandatory_result = self._process_review_result(mandatory_result)
        design_value_result = self._process_review_result(design_value_result)
        technical_param_result = self._process_review_result(technical_param_result)

        return {
            'mandatory_standards': mandatory_result,
            'design_values': design_value_result,
            'technical_parameters': technical_param_result,
            'overall_score': self._calculate_technical_score(mandatory_result, design_value_result, technical_param_result)
        }

    async def rag_enhanced_check(self, unit_content: Dict[str, Any]) -> Dict[str, Any]:
        """
        RAG增强审查

        Args:
            unit_content: 待审查单元内容

        Returns:
            Dict[str, Any]: RAG增强审查结果
        """
        # 向量检索
        vector_results = await self.vector_search(unit_content['content'])

        # 混合检索
        hybrid_results = await self.hybrid_search(unit_content['content'])

        # 重排序
        reranked_results = await self.rerank_results(unit_content['content'], hybrid_results)

        return {
            'vector_search': vector_results,
            'hybrid_search': hybrid_results,
            'reranked_results': reranked_results,
            'enhanced_suggestions': self.generate_enhanced_suggestions(reranked_results)
        }


    async def check_grammar(self, trace_id_idx: str, review_content: str = None, review_references: str = None,
                          stage_name: str = None, state: dict = None, current_progress: int = None) -> Dict[str, Any]:
        """
        词句语法检查

        Args:
            trace_id_idx: 追踪ID索引
            review_content: 审查内容
            review_references: 审查参考信息
            stage_name: 阶段名称
            state: 状态字典
            current_progress: 当前进度

        Returns:
            Dict[str, Any]: 语法检查结果
        """
        reviewer_type = Stage.BASIC.value['reviewer_type']
        prompt_name = Stage.BASIC.value['sensitive']
        trace_id = prompt_name+trace_id_idx
        return await self.review("词句语法检查", trace_id, reviewer_type, prompt_name, review_content, review_references,
                               stage_name, state, current_progress)

    async def check_semantic_logic(self, trace_id_idx: str, review_content: str = None, review_references: str = None,
                                 stage_name: str = None, state: dict = None, current_progress: int = None) -> Dict[str, Any]:
        """
        语义逻辑检查

        Args:
            trace_id_idx: 追踪ID索引
            review_content: 审查内容
            review_references: 审查参考信息
            stage_name: 阶段名称
            state: 状态字典
            current_progress: 当前进度

        Returns:
            Dict[str, Any]: 语义逻辑检查结果
        """
        reviewer_type = Stage.BASIC.value['reviewer_type']
        prompt_name = Stage.BASIC.value['semantic']
        trace_id = prompt_name+trace_id_idx
        return await self.review("语义逻辑检查", trace_id, reviewer_type, prompt_name, review_content, review_references,
                               stage_name, state, current_progress)

    async def check_completeness(self, trace_id_idx: str, review_content: str = None, review_references: str = None,
                               stage_name: str = None, state: dict = None, current_progress: int = None) -> Dict[str, Any]:
        """
        完整性检查

        Args:
            trace_id_idx: 追踪ID索引
            review_content: 审查内容
            review_references: 审查参考信息
            stage_name: 阶段名称
            state: 状态字典
            current_progress: 当前进度

        Returns:
            Dict[str, Any]: 完整性检查结果
        """
        reviewer_type = Stage.BASIC.value['reviewer_type']
        prompt_name = Stage.BASIC.value['completeness']
        trace_id = prompt_name+trace_id_idx
        return await self.review("完整性检查", trace_id, reviewer_type, prompt_name, review_content, review_references,
                               stage_name, state, current_progress)

    async def check_mandatory_standards(self, trace_id_idx: str, review_content: str = None, review_references: str = None,
                                        stage_name: str = None, state: dict = None, current_progress: int = None) -> Dict[str, Any]:
        """
        强制性标准检查

        Args:
            trace_id_idx: 追踪ID索引
            review_content: 审查内容
            review_references: 审查参考信息
            stage_name: 阶段名称
            state: 状态字典
            current_progress: 当前进度

        Returns:
            Dict[str, Any]: 强制性标准检查结果
        """
        reviewer_type = Stage.TECHNICAL.value['reviewer_type']
        prompt_name = Stage.TECHNICAL.value['mandatory']
        trace_id = prompt_name+trace_id_idx
        return await self.review("强制性标准检查", trace_id, reviewer_type, prompt_name, review_content, review_references,
                               stage_name, state, current_progress)

    async def check_design_values(self, trace_id_idx: str, review_content: str = None, review_references: str = None,
                                  stage_name: str = None, state: dict = None, current_progress: int = None) -> Dict[str, Any]:
        """
        设计值检查

        Args:
            trace_id_idx: 追踪ID索引
            review_content: 审查内容
            review_references: 审查参考信息
            stage_name: 阶段名称
            state: 状态字典
            current_progress: 当前进度

        Returns:
            Dict[str, Any]: 设计值检查结果
        """
        reviewer_type = Stage.TECHNICAL.value['reviewer_type']
        prompt_name = Stage.TECHNICAL.value['design']
        trace_id = prompt_name+trace_id_idx
        return await self.review("设计值检查", trace_id, reviewer_type, prompt_name, review_content, review_references,
                               stage_name, state, current_progress)

    async def check_technical_parameters(self, trace_id_idx: str, review_content: str = None, review_references: str = None,
                                         stage_name: str = None, state: dict = None, current_progress: int = None) -> Dict[str, Any]:
        """
        技术参数检查

        Args:
            trace_id_idx: 追踪ID索引
            review_content: 审查内容
            review_references: 审查参考信息
            stage_name: 阶段名称
            state: 状态字典
            current_progress: 当前进度

        Returns:
            Dict[str, Any]: 技术参数检查结果
        """
        reviewer_type = Stage.TECHNICAL.value['reviewer_type']
        prompt_name = Stage.TECHNICAL.value['technical']
        trace_id = prompt_name+trace_id_idx
        return await self.review("技术参数检查", trace_id, reviewer_type, prompt_name, review_content, review_references,
                               stage_name, state, current_progress)

    # RAG检索增强
    async def vector_search(self, content: str) -> List[Dict[str, Any]]:
        """
        向量检索

        Args:
            content: 检索内容

        Returns:
            List[Dict[str, Any]]: 向量检索结果列表
        """
        await asyncio.sleep(0.1)
        return [{"similarity": 0.85, "content": "相关标准1"}, {"similarity": 0.78, "content": "相关标准2"}]

    async def hybrid_search(self, content: str) -> List[Dict[str, Any]]:
        """
        混合检索

        Args:
            content: 检索内容

        Returns:
            List[Dict[str, Any]]: 混合检索结果列表
        """
        await asyncio.sleep(0.2)
        return [{"score": 0.88, "content": "混合检索结果1"}, {"score": 0.82, "content": "混合检索结果2"}]

    async def rerank_results(self, content: str, results: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """
        重排序

        Args:
            content: 原始内容
            results: 待重排序的结果列表

        Returns:
            List[Dict[str, Any]]: 重排序后的结果列表
        """
        await asyncio.sleep(0.1)
        return sorted(results, key=lambda x: x.get('score', 0), reverse=True)[:5]

    def generate_enhanced_suggestions(self, results: List[Dict[str, Any]]) -> List[str]:
        """
        生成增强建议

        Args:
            results: 检索结果列表

        Returns:
            List[str]: 增强建议列表
        """
        suggestions = []
        for result in results:
            suggestions.append(f"基于{result.get('content', '相关内容')}的建议")
        return suggestions

    def _calculate_basic_score(self, grammar: Dict, semantic: Dict, completeness: Dict) -> float:
        """
        计算基础合规性得分

        Args:
            grammar: 语法检查结果
            semantic: 语义检查结果
            completeness: 完整性检查结果

        Returns:
            float: 基础合规性平均得分
        """
        return (grammar.get('score', 0) + semantic.get('score', 0) + completeness.get('score', 0)) / 3

    def _calculate_technical_score(self, mandatory: Dict, design: Dict, technical: Dict) -> float:
        """
        计算技术合规性得分

        Args:
            mandatory: 强制性标准检查结果
            design: 设计值检查结果
            technical: 技术参数检查结果

        Returns:
            float: 技术合规性平均得分
        """
        return (mandatory.get('compliance_rate', 0) + design.get('accuracy', 0) + technical.get('precision', 0)) / 3

    def _calculate_overall_risk(self, basic: Dict, technical: Dict, rag: Dict) -> str:
        """
        计算总体风险等级

        Args:
            basic: 基础合规性结果
            technical: 技术合规性结果
            rag: RAG增强审查结果

        Returns:
            str: 风险等级 ("low", "medium", "high")
        """
        basic_score = basic.get('overall_score', 0)
        technical_score = technical.get('overall_score', 0)

        # 如果RAG被禁用或有错误，忽略它
        if 'error' in rag:
            avg_score = (basic_score + technical_score) / 2
        else:
            rag_score = rag.get('overall_score', 0)
            avg_score = (basic_score + technical_score + rag_score) / 3

        if avg_score >= 90:
            return "low"
        elif avg_score >= 70:
            return "medium"
        else:
            return "high"

    def _aggregate_results(self, results: List[ReviewResult]) -> Dict[str, Any]:
        """
        汇总审查结果

        Args:
            results: 审查结果列表

        Returns:
            Dict[str, Any]: 汇总后的统计结果
        """
        risk_counts = {"high": 0, "medium": 0, "low": 0}

        for result in results:
            risk_counts[result.overall_risk] += 1

        return {
            "risk_distribution": risk_counts,
            "total_issues": len([r for r in results if r.overall_risk != "low"]),
            "high_risk_count": risk_counts["high"],
            "medium_risk_count": risk_counts["medium"],
            "low_risk_count": risk_counts["low"]
        }