from typing import Optional from fastapi import APIRouter, Depends, Request from sqlmodel import Session from api.platform_shared import ( apply_platform_runtime_changes, cached_platform_overview_payload, invalidate_platform_nodes_cache, invalidate_platform_overview_cache, store_platform_overview_payload, ) from core.database import get_session from providers.selector import get_runtime_provider from services.platform_activity_service import list_activity_events from services.platform_analytics_service import build_dashboard_analytics from services.platform_overview_service import build_platform_overview from services.platform_usage_service import list_usage router = APIRouter() @router.get("/api/platform/overview") def get_platform_overview(request: Request, session: Session = Depends(get_session)): cached_payload = cached_platform_overview_payload() if cached_payload is not None: return cached_payload def _read_runtime(bot): provider = get_runtime_provider(request.app.state, bot) status = str(provider.get_runtime_status(bot_id=str(bot.id or "")) or "STOPPED").upper() runtime = dict(provider.get_resource_snapshot(bot_id=str(bot.id or "")) or {}) runtime.setdefault("docker_status", status) return status, runtime payload = build_platform_overview(session, read_runtime=_read_runtime) return store_platform_overview_payload(payload) @router.post("/api/platform/cache/clear") def clear_platform_cache(): invalidate_platform_overview_cache() invalidate_platform_nodes_cache() return {"status": "cleared"} @router.post("/api/platform/reload") def reload_platform_runtime(request: Request): apply_platform_runtime_changes(request) return {"status": "reloaded"} @router.get("/api/platform/usage") def get_platform_usage( bot_id: Optional[str] = None, limit: int = 100, offset: int = 0, session: Session = Depends(get_session), ): return list_usage(session, bot_id=bot_id, limit=limit, offset=offset) @router.get("/api/platform/dashboard-analytics") def get_platform_dashboard_analytics( since_days: int = 7, events_limit: int = 20, session: Session = Depends(get_session), ): return build_dashboard_analytics(session, since_days=since_days, events_limit=events_limit) @router.get("/api/platform/events") def get_platform_events( bot_id: Optional[str] = None, limit: int = 100, offset: int = 0, session: Session = Depends(get_session), ): return list_activity_events(session, bot_id=bot_id, limit=limit, offset=offset)