from fastapi import APIRouter, Depends, HTTPException, Query

from app.core.deps import require_role
from app.models import User
from app.schemas.common import ApiResponse
from app.services import task_center_service


router = APIRouter()
_admin = require_role("admin", "super_admin")


@router.get("/tasks", response_model=ApiResponse)
async def list_tasks(_: User = Depends(_admin)):
    return ApiResponse(data=await task_center_service.list_tasks())


@router.get("/tasks/runs", response_model=ApiResponse)
async def list_task_runs(
    task_key: str | None = Query(None),
    status: str | None = Query(None),
    trigger_type: str | None = Query(None),
    offset: int = Query(0, ge=0),
    limit: int = Query(50, ge=1, le=200),
    _: User = Depends(_admin),
):
    data = await task_center_service.list_task_runs(
        task_key=task_key,
        status=status,
        trigger_type=trigger_type,
        offset=offset,
        limit=limit,
    )
    return ApiResponse(data=data)


@router.post("/tasks/{task_key}/run", response_model=ApiResponse)
async def run_task_now(task_key: str, admin_user: User = Depends(_admin)):
    try:
        data = await task_center_service.run_task(task_key, trigger_type="manual", operator_id=admin_user.id)
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    except Exception as exc:
        raise HTTPException(status_code=500, detail=f"任务执行失败：{exc}") from exc
    return ApiResponse(data=data)
