from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException
from loguru import logger
from session_hub_fastapi.models.session_hub import HealthStatus, HostInfo, Stats

from session_hub_api.dependencies import get_query_api
from session_hub_api.mapping import host_info, stats
from session_hub_core.query import QueryAPI

router = APIRouter(tags=["System"])


@router.get("/api/stats", response_model=Stats)
async def get_stats(query_api: Annotated[QueryAPI, Depends(get_query_api)]) -> Stats:
    return stats(await query_api.get_stats())


@router.get("/api/hosts", response_model=list[HostInfo])
async def get_hosts(query_api: Annotated[QueryAPI, Depends(get_query_api)]) -> list[HostInfo]:
    hosts = await query_api.get_hosts()
    return [host_info(info) for info in hosts]


@router.get("/health", response_model=HealthStatus)
async def get_health(query_api: Annotated[QueryAPI, Depends(get_query_api)]) -> HealthStatus:
    try:
        await query_api.get_hosts()
    except Exception as exc:
        logger.warning("health probe failed: {}", exc)
        raise HTTPException(status_code=503, detail="database unreachable") from exc
    return HealthStatus(status="ok")
