"""Phase 5B: Marketplace reputation/uptime API (issue #308).

GET /api/marketplace/uptime — returns { device_id: uptime_pct } for last 30 days
from probe store. Used by frontend GET /api/marketplace/nodes to add uptime_pct and tier.
"""

from __future__ import annotations

from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse

router = APIRouter(prefix="/api/marketplace", tags=["marketplace"])


@router.get("/uptime")
async def get_uptime(request: Request, days: int = 30) -> JSONResponse:
    """Return uptime % per device for last *days* days (from synthetic probes).

    Response: { "uptime": { "<device_id>": <0-100>, ... } }
    If probe store is not available, returns { "uptime": {} }.
    """
    store = getattr(request.app.state, "probe_store", None)
    if store is None:
        return JSONResponse(content={"uptime": {}})
    try:
        uptime_map = await store.get_uptime_map(device_ids=None, days=days)
        return JSONResponse(content={"uptime": uptime_map})
    except Exception:
        return JSONResponse(content={"uptime": {}}, status_code=500)
