"""
语义逻辑审查模块
使用通用模型底座进行语义逻辑检查
"""

import time
import asyncio
from typing import Dict, Any
from core.construction_review.component.reviewers.base_reviewer import ReviewResult
from core.construction_review.component.reviewers.utils.prompt_loader import prompt_loader
from foundation.ai.agent.generate.model_generate import generate_model_client
from foundation.observability.logger.loggering import review_logger as logger


class SemanticLogicReviewer:
    """语义逻辑审查器"""

    def __init__(self):
        """初始化语义逻辑审查器"""
        self.model_client = generate_model_client
        
    async def check_semantic_logic(
        self,
        trace_id: str,
        review_content: str,
        state: Dict[str, Any] = None,
        stage_name: str = None
    ) -> ReviewResult:
        """
        执行语义逻辑检查

        Args:
            trace_id: 追踪ID
            review_content: 待审查内容
            state: 状态字典（包含progress_manager和callback_task_id）
            stage_name: 阶段名称

        Returns:
            ReviewResult: 审查结果对象
        """
        start_time = time.time()
        
        try:
            logger.info(f"开始语义逻辑检查，trace_id: {trace_id}, 内容长度: {len(review_content)}")
            
            # 构造提示词参数
            prompt_kwargs = {}
            prompt_kwargs["review_content"] = review_content
            prompt_kwargs["review_references"] = ""  # ✅ 添加空字符串，避免模板格式化错误

            # 获取提示词模板
            prompt_template = prompt_loader.get_prompt_template(
                "basic",
                "semantic_logic_check",
                **prompt_kwargs
            )
            
            # 格式化提示词消息
            messages = prompt_template.format_messages()

            logger.info("调用语义逻辑检查模型")

            # 使用 function_name 从 model_setting.yaml 加载模型配置
            model_response = await self.model_client.get_model_generate_invoke(
                trace_id=trace_id,
                messages=messages,
                function_name="grammar_check"
            )
            
            logger.info(f"语义逻辑检查模型响应成功，响应长度: {len(model_response)}")
            
            # 计算执行时间
            execution_time = time.time() - start_time
            
            # 构造审查结果
            result = ReviewResult(
                success=True,
                details={
                    "name": "semantic_logic_check",
                    "response": model_response
                },
                error_message=None,
                execution_time=execution_time
            )
            
            # 推送审查完成信息
            if state and state.get("progress_manager"):
                review_result_data = {
                    'name': 'semantic_logic_check',
                    'success': result.success,
                    'details': result.details,
                    'error_message': result.error_message,
                    'execution_time': result.execution_time,
                    'timestamp': time.time()
                }
                
                asyncio.create_task(
                    state["progress_manager"].update_stage_progress(
                        callback_task_id=state["callback_task_id"],
                        stage_name=stage_name,
                        current=None,
                        status="processing",
                        message=f"semantic_logic_check 审查完成，耗时: {result.execution_time:.2f}s",
                        issues=[review_result_data],
                        event_type="processing"
                    )
                )
                
            logger.info(f"semantic_logic_check 审查完成，耗时: {result.execution_time:.2f}s")
            
            return result
            
        except Exception as e:
            execution_time = time.time() - start_time
            error_msg = f"语义逻辑检查失败: {str(e)}"
            logger.error(error_msg, exc_info=True)
            
            # 返回失败结果
            result = ReviewResult(
                success=False,
                details={"name": "semantic_logic_check"},
                error_message=error_msg,
                execution_time=execution_time
            )
            
            # 推送失败信息
            if state and state.get("progress_manager"):
                review_result_data = {
                    'name': 'semantic_logic_check',
                    'success': False,
                    'details': result.details,
                    'error_message': error_msg,
                    'execution_time': execution_time,
                    'timestamp': time.time()
                }
                
                asyncio.create_task(
                    state["progress_manager"].update_stage_progress(
                        callback_task_id=state["callback_task_id"],
                        stage_name=stage_name,
                        current=None,
                        status="processing",
                        message=f"semantic_logic_check 审查失败: {error_msg}",
                        issues=[review_result_data],
                        event_type="processing"
                    )
                )
            
            return result


# 全局单例实例
semantic_logic_reviewer = SemanticLogicReviewer()
