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

from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel
from typing import Dict, Any
from foundation.observability.cachefiles import cache, CacheBaseDir


# 导入文件上传模块的存储
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]


review_results_router = APIRouter(prefix="/sgsc", tags=["前端接口"])

@review_results_router.get("/review_results", response_model=ReviewResultsResponse)
async def review_results(
    callback_task_id: str = Query(..., description="回调任务ID"),
    user: str = Query(..., description="用户ID")
):
    """
    获取审查结果接口 - 从temp目录读取保存的结果文件
    """
    try:
        # 验证参数
        if not callback_task_id:
            raise HTTPException(status_code=400, detail="缺少callback_task_id参数")

        if not user:
            raise HTTPException(status_code=400, detail="缺少user参数")

        # 验证用户标识（应该是指定用户如user-001）
        valid_users = {"user-001", "user-002", "user-003"}  # 可以配置化
        if user not in valid_users:
            raise HTTPException(status_code=403, detail="无效的用户ID")

        # 使用 cache_manager 读取结果文件
        review_results = cache.load(
            subdir="final_result",
            filename=f"{callback_task_id}.json",
            base_cache_dir=CacheBaseDir.CONSTRUCTION_REVIEW,
            default=None
        )

        if review_results is None:
            raise HTTPException(status_code=404, detail="审查结果文件不存在")

        # 验证文件中的用户信息是否匹配
        if review_results.get("user_id") != user:
            raise HTTPException(status_code=403, detail="用户权限验证失败")

        return ReviewResultsResponse(
            code=200,
            data=review_results
        )

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"服务器内部错误: {str(e)}")
