"""
审查结果获取接口Mock实现
模拟风险统计、总结报告和问题条文返回
"""

import uuid
import random
from datetime import datetime
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Optional, Dict, Any
from .schemas.error_schemas import ReviewResultsErrors
review_results_router = APIRouter(prefix="/sgsc", tags=["审查结果Mock"])

# 导入文件上传模块的存储
try:
    from .file_upload import uploaded_files
except ImportError:
    from views.construction_review.file_upload import uploaded_files

class ReviewResultsRequest(BaseModel):
    id: str = None
    user: str = None
    type: str = None  # "summary" 或 "issues"

class ReviewResultsResponse(BaseModel):
    code: int
    data: Dict[str, Any]

def generate_risk_stats():
    """生成模拟风险统计"""
    return {
        "high": random.randint(1, 5),
        "medium": random.randint(3, 8),
        "low": random.randint(2, 6)
    }

def generate_dimension_scores():
    """生成模拟四维评分"""
    return {
        "safety": random.randint(60, 95),
        "quality": random.randint(55, 90),
        "schedule": random.randint(70, 95),
        "cost": random.randint(65, 90)
    }

def generate_summary_report(risk_stats):
    """生成模拟总结报告"""
    total_issues = sum(risk_stats.values())
    if risk_stats["high"] > 0:
        return f"该施工方案存在{risk_stats['high']}处高风险问题，需重点整改。建议在施工前完善相关技术细节，确保符合规范要求。"
    elif total_issues > 5:
        return f"该施工方案整体符合规范要求，但存在{total_issues}处中低风险问题，建议优化完善。"
    else:
        return "该施工方案整体符合规范要求，存在少量细节问题，可正常施工。"

def generate_issues():
    """生成模拟问题条文"""
    issues = []

    # 高风险问题示例
    high_risk_issues = [
        {
            "page": 12,
            "chapter": "1.1 路面材料要求",
            "original_content": "采用沥青、混凝土作为路面施工材料，未明确标号及来源；施工段落仅标注主线段，未细化具体桩号范围"
        },
        {
            "page": 45,
            "chapter": "3.2 模板安装工艺",
            "original_content": "模板未按设计要求进行预压，直接浇筑混凝土；预压观测记录采用文字描述，未体现观测点布置及沉降数据"
        }
    ]

    # 中风险问题示例
    medium_risk_issues = [
        {
            "page": 28,
            "chapter": "2.3 施工机械配置",
            "original_content": "施工机械清单未包含备用设备，未制定设备故障应急预案"
        },
        {
            "page": 67,
            "chapter": "4.1 质量保证措施",
            "original_content": "质量检测频次未明确具体标准，检验方法描述不够详细"
        }
    ]

    # 生成高风险问题
    for i, issue_data in enumerate(high_risk_issues):
        issue_id = f"ISSUE-HL-{datetime.now().strftime('%Y%m%d')}-{i+1:03d}"

        reviews = [
            {
                "check_item": "强制性标准符合性检查",
                "check_result": "不符合",
                "risk_info": {"risk_level": "high"},
                "suggestion": {
                    "suggestion_type": "professional",
                    "suggestion_content": "按相关规范要求，明确材料规格和施工参数，确保符合技术标准要求",
                    "verification_standard": "整改后需提供技术规格书，由项目总工签字确认"
                }
            },
            {
                "check_item": "条文完整性检查",
                "check_result": "不符合",
                "risk_info": {"risk_level": "low"},
                "suggestion": {
                    "suggestion_type": "completeness",
                    "suggestion_content": "补充详细的施工范围描述，与施工平面布置图桩号标注一致",
                    "verification_standard": "参考施工方案编制导则相关条款"
                }
            }
        ]

        issues.append({
            "issue_id": issue_id,
            "metadata": issue_data,
            "risk_summary": {
                "max_risk_level": "high",
                "risk_count": {"high": 1, "medium": 1, "low": 1},
                "key_risk_reminder": "高风险点：技术参数缺失，需24小时内整改"
            },
            "review_lists": reviews
        })

    # 生成中风险问题
    for i, issue_data in enumerate(medium_risk_issues):
        issue_id = f"ISSUE-ML-{datetime.now().strftime('%Y%m%d')}-{i+1:03d}"

        reviews = [
            {
                "check_item": "规范性检查",
                "check_result": "不符合",
                "risk_info": {"risk_level": "medium"},
                "suggestion": {
                    "suggestion_type": "normative",
                    "suggestion_content": "完善应急预案制定，明确设备故障处理流程和备用资源配置",
                    "verification_standard": "参考《施工组织设计规范》相关要求"
                }
            }
        ]

        issues.append({
            "issue_id": issue_id,
            "metadata": issue_data,
            "risk_summary": {
                "max_risk_level": "medium",
                "risk_count": {"high": 0, "medium": 1, "low": 0},
                "key_risk_reminder": "中风险点：管理措施不完善，需在施工前完善"
            },
            "review_lists": reviews
        })

    return issues

@review_results_router.post("/review_results", response_model=ReviewResultsResponse)
async def review_results(request: ReviewResultsRequest):
    """
    Mock审查结果获取接口
    """
    try:
        # 验证参数
        if not request.type or request.type not in ["summary", "issues"]:
            raise ReviewResultsErrors.invalid_type()

        if not request.id or not isinstance(request.id, str):
            raise ReviewResultsErrors.missing_param_id()

        # 验证UUID格式（简单检查）
        if len(request.id) != 36 or request.id.count('-') != 4:
            raise ReviewResultsErrors.invalid_id_format()

        # 验证用户标识（应该是指定用户如user-001）
        valid_users = {"user-001", "user-002", "user-003"}  # 可以配置化
        if not request.user or request.user not in valid_users:
            raise ReviewResultsErrors.invalid_user()

        # 检查文档是否存在
        if request.id not in uploaded_files:
            raise ReviewResultsErrors.task_not_found()

        # 验证用户权限
        file_info = uploaded_files[request.id]
        if file_info.get("user") != request.user:
            raise ReviewResultsErrors.invalid_user()

        # 检查任务状态（模拟：只有完成的任务才能查看结果）
        callback_task_id = file_info.get("callback_task_id")
        if callback_task_id in uploaded_files:
            task_info = uploaded_files[callback_task_id]
            if task_info.get("review_task_status") != "completed":
                raise ReviewResultsErrors.no_review_results()

        # 根据类型返回结果
        if request.type == "summary":
            risk_stats = generate_risk_stats()
            dimension_scores = generate_dimension_scores()
            summary_report = generate_summary_report(risk_stats)

            return ReviewResultsResponse(
                code=200,
                data={
                    "risk_stats": risk_stats,
                    "dimension_scores": dimension_scores,
                    "summary_report": summary_report,
                    "multidimensional_report": summary_report + "建议重点关注安全管理和质量控制措施的落实。"
                }
            )

        else:  # issues
            issues = generate_issues()

            return ReviewResultsResponse(
                code=200,
                data={
                    "issues": issues
                }
            )

    except HTTPException:
        raise
    except Exception as e:
        raise ReviewResultsErrors.server_error(e)
