import modal
from fastapi import APIRouter, Depends, HTTPException
from loguru import logger
from starlette import status

from ..middleware.authorization import verify_token, nakama_login
from ..models.requests.models import NakamaLogin
from ..models.responses.models import ModalTaskCancelResponse, NakamaJWTResponse

router = APIRouter(prefix="/task", tags=["tasks"])


@router.get("/cancel/{task_id}", summary="终止任务",
            description="终止任务, 无论是正在排队还是真正运行",
            dependencies=[Depends(verify_token)])
async def task_cancel(task_id: str) -> ModalTaskCancelResponse:
    try:
        fn_call = modal.FunctionCall.from_id(task_id)
        fn_call.cancel()
        return ModalTaskCancelResponse(success=True)
    except Exception as e:
        logger.exception(e)
        return ModalTaskCancelResponse(success=False,
                                       error=e.message if hasattr(e, 'message') else str(e))


@router.post("/oauth", summary="登录以获取Nakama JWT")
async def nakama_oauth(body: NakamaLogin) -> NakamaJWTResponse:
    try:
        return nakama_login(body.email, body.password)
    except Exception as e:
        logger.exception(e)
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="账号无法登录")
