"""Monitoring API router (P4-M3). Real-time scheduler statistics, queue/running/history endpoints. """ from fastapi import APIRouter, HTTPException from typing import Any, Dict, List, Optional from ..services.batch_scheduler import get_scheduler router = APIRouter(prefix="/api/monitor", tags=["monitor"]) @router.get("/stats") async def get_stats() -> Dict[str, Any]: """Get real-time scheduler statistics.""" scheduler = get_scheduler() return scheduler.get_statistics() @router.get("/queue") async def get_queue(limit: int = 50) -> Dict[str, Any]: """Get queued tasks list.""" scheduler = get_scheduler() stats = scheduler.get_statistics() return {"tasks": stats.get("queued_tasks", [])[:limit], "count": stats.get("queued_count", 0)} @router.get("/running") async def get_running() -> Dict[str, Any]: """Get currently running tasks.""" scheduler = get_scheduler() stats = scheduler.get_statistics() return {"tasks": stats.get("running_tasks", []), "count": stats.get("running_count", 0)} @router.get("/history") async def get_history(limit: int = 50) -> Dict[str, Any]: """Get recently completed tasks.""" scheduler = get_scheduler() stats = scheduler.get_statistics() return {"tasks": stats.get("recent_completed", [])[-limit:], "count": stats.get("completed_count", 0)} @router.post("/cancel/{task_id}") async def cancel_task(task_id: str) -> Dict[str, Any]: """Cancel a queued or running task.""" scheduler = get_scheduler() success = scheduler.cancel_task(task_id) if not success: raise HTTPException(status_code=404, detail=f"Task {task_id} not found in queue or running") return {"success": True, "task_id": task_id, "message": "Task cancelled"} @router.get("/health") async def health_check() -> Dict[str, Any]: """System health check.""" import os import platform return { "status": "healthy", "platform": platform.system(), "python_version": platform.python_version(), "scheduler_active": get_scheduler() is not None, "timestamp": __import__("datetime").datetime.now().isoformat(), }