from __future__ import annotations

from fastapi import APIRouter, HTTPException, Request
from starlette.responses import RedirectResponse

from app.db import crud
from app.db.engine import get_session
from app.tasks.execute import execute_job


router = APIRouter()


@router.post("/admin/joblogs/{log_id}/retry")
def retry_joblog(request: Request, log_id: int):
    session = get_session()
    try:
        log = crud.get_job_log(session, log_id)
        if not log:
            raise HTTPException(status_code=404, detail="JobLog not found")
        # 关键：用 snapshot_params 重新触发任务（其中 secret_cfg 仍为密文）
        execute_job.delay(snapshot_params=log.snapshot_params)
    finally:
        session.close()

    referer = request.headers.get("Referer") or "/admin"
    return RedirectResponse(referer, status_code=303)


@router.post("/admin/jobs/{job_id}/run")
def run_job(request: Request, job_id: str):
    # 触发一次立即执行
    execute_job.delay(job_id=job_id)
    referer = request.headers.get("Referer") or "/admin"
    return RedirectResponse(referer, status_code=303)


