from fastapi import APIRouter, Query from app.config import CPS_LOG_PATH import json router = APIRouter() @router.get("/timeline") async def get_cps_timeline(hours: int = Query(default=24, ge=1, le=720)): """CPS data points for the last N hours.""" if not CPS_LOG_PATH.exists(): return {"data_points": [], "hours": hours} from datetime import datetime, timedelta cutoff = datetime.now() - timedelta(hours=hours) data_points = [] try: with open(CPS_LOG_PATH) as f: for line in f: line = line.strip() if not line: continue try: entry = json.loads(line) ts = datetime.fromisoformat(entry["ts"]) if ts >= cutoff: data_points.append(entry) except (json.JSONDecodeError, KeyError, ValueError): continue except OSError: return {"data_points": [], "hours": hours} return { "hours": hours, "data_points": data_points, }