from fastapi import APIRouter, Depends, HTTPException, status
from typing import Optional

from app.controllers.user_valuation import user_valuation_controller
from app.schemas.valuation import (
    UserValuationCreate,
    UserValuationQuery,
    UserValuationList,
    UserValuationOut,
    UserValuationDetail
)
from app.schemas.base import Success, SuccessExtra
from app.utils.app_user_jwt import get_current_app_user_id

app_valuations_router = APIRouter(tags=["用户端估值评估"])


@app_valuations_router.post("/", summary="创建估值评估")
async def create_valuation(
    data: UserValuationCreate,
    user_id: int = Depends(get_current_app_user_id)
):
    """
    用户创建估值评估申请
    """
    try:
        result = await user_valuation_controller.create_valuation(
            user_id=user_id,
            data=data
        )
        # 使用model_dump_json()来正确序列化datetime，然后解析为dict
        import json
        result_dict = json.loads(result.model_dump_json())
        return Success(data=result_dict, msg="估值评估申请提交成功")
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建估值评估失败: {str(e)}"
        )


@app_valuations_router.get("/", summary="获取我的估值评估列表")
async def get_my_valuations(
    query: UserValuationQuery = Depends(),
    user_id: int = Depends(get_current_app_user_id)
):
    """
    获取当前用户的估值评估列表
    """
    try:
        result = await user_valuation_controller.get_user_valuations(
            user_id=user_id,
            query=query
        )
        # 使用model_dump_json()来正确序列化datetime，然后解析为dict列表
        import json
        serialized_items = [json.loads(item.model_dump_json()) for item in result.items]
        return SuccessExtra(
            data=serialized_items,
            total=result.total,
            page=result.page,
            size=result.size,
            pages=result.pages,
            msg="获取估值评估列表成功"
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取估值评估列表失败: {str(e)}"
        )


@app_valuations_router.get("/{valuation_id}", summary="获取估值评估详情")
async def get_valuation_detail(
    valuation_id: int,
    user_id: int = Depends(get_current_app_user_id)
):
    """
    获取指定估值评估的详细信息
    """
    try:
        result = await user_valuation_controller.get_user_valuation_detail(
            user_id=user_id,
            valuation_id=valuation_id
        )
        
        if not result:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="估值评估记录不存在"
            )
        
        # 使用model_dump_json()来正确序列化datetime，然后解析为dict
        import json
        result_dict = json.loads(result.model_dump_json())
        return Success(data=result_dict, msg="获取估值评估详情成功")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取估值评估详情失败: {str(e)}"
        )


@app_valuations_router.get("/statistics/overview", summary="获取我的估值评估统计")
async def get_my_valuation_statistics(
    user_id: int = Depends(get_current_app_user_id)
):
    """
    获取当前用户的估值评估统计信息
    """
    try:
        result = await user_valuation_controller.get_user_valuation_statistics(
            user_id=user_id
        )
        return Success(data=result, msg="获取统计信息成功")
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取统计信息失败: {str(e)}"
        )