import modal
from fastapi import APIRouter, Depends
from loguru import logger

from ..middleware.authorization import verify_token
from ..models.web_model import ModalTaskCancelResponse

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


@router.get("/cancel/{task_id}", summary="终止任务", description="终止任务, 无论是正在排队还是真正运行")
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))
