from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app import models, schemas
from app.database import get_db
from app.services.task_runner import TaskRunner

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


@router.get("/runs", response_model=list[schemas.TaskRunRead])
def list_task_runs(db: Session = Depends(get_db)) -> list[models.TaskRun]:
    return db.query(models.TaskRun).order_by(models.TaskRun.created_at.desc()).limit(100).all()


@router.get("/runs/{task_id}", response_model=schemas.TaskRunRead)
def get_task_run(task_id: int, db: Session = Depends(get_db)) -> models.TaskRun:
    task = db.get(models.TaskRun, task_id)
    if not task:
        raise HTTPException(status_code=404, detail="任务不存在")
    return task


@router.post("/run-now", response_model=schemas.TaskRunRead)
async def run_now(db: Session = Depends(get_db)) -> models.TaskRun:
    runner = TaskRunner()
    return await runner.run(db, task_type=models.TaskType.manual_scan)

