from fastapi import APIRouter, Depends
from app.models.user import User
from app.routers.auth import get_current_user
from app.services.scheduler_service import (
    get_scheduler_status,
    scheduler,
    daily_task_analysis,
    forum_scan_task,
    graph_rebuild_task,
    tag_generation_task,
)
import logging

router = APIRouter(prefix="/api/scheduler", tags=["定时任务"])
logger = logging.getLogger(__name__)


@router.get("/status")
async def get_status(current_user: User = Depends(get_current_user)):
    """获取调度器状态"""
    return get_scheduler_status()


@router.post("/trigger/{job_id}")
async def trigger_job(job_id: str, current_user: User = Depends(get_current_user)):
    """手动触发某个定时任务"""
    job_map = {
        "daily_task_analysis": daily_task_analysis,
        "forum_scan": forum_scan_task,
        "graph_rebuild": graph_rebuild_task,
        "tag_generation": tag_generation_task,
    }

    if job_id not in job_map:
        return {"error": f"未知任务: {job_id}"}

    try:
        await job_map[job_id]()
        return {"status": "ok", "job": job_id, "message": "任务已触发执行"}
    except Exception as e:
        logger.error(f"手动触发任务失败 {job_id}: {e}")
        return {"status": "error", "job": job_id, "error": str(e)}
