"""Rankings over `metrics_current` with window deltas from `metric_series` (pricing_changes counts events in the window).""" from __future__ import annotations from typing import Any from fastapi import APIRouter, Query, Request from companyatlas.api import aggregates as agg from companyatlas.api.common import cached, cached_response from companyatlas.db import connection ORDER = 20 router = APIRouter(prefix="/api/v1", tags=["rankings"]) KINDS = "|".join(agg.RANKING_KINDS) @router.get("/rankings", summary="Ranked companies by kind and window (cached 120 s)") async def rankings(request: Request, kind: str = Query("most_active", pattern=f"^({KINDS})$"), window: str = Query("7d", pattern="^(24h|7d|30d|90d|1y)$"), country: str | None = Query(None, max_length=2), industry: str | None = Query(None, max_length=80), limit: int = Query(50, ge=1, le=200), sparkline: str | None = None) -> Any: spark = sparkline in ("1", "true", "yes") async def produce() -> dict[str, Any]: async with connection() as conn: items = await agg.ranking_cards(conn, kind, window, country=(country or None), industry=(industry or None), limit=limit, sparkline=spark) return {"kind": kind, "window": window, "country": (country or "").upper() or None, "industry": industry or None, "items": items, "kinds": list(agg.RANKING_KINDS)} key = f"rankings:{kind}:{window}:{(country or '').upper()}:{industry or ''}:{limit}:{int(spark)}" return cached_response(request, await cached(key, 120, produce), 120)