"""Events and health monitoring router.

Provides endpoints for the centralized trading event log and live health summary.
"""
from __future__ import annotations

from typing import Any

from fastapi import APIRouter, Query

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


def _get_store():
    from apps.web.services.events_store import EventsStore
    return EventsStore.get()


@router.get("")
def list_events(
    source: str | None = Query(None),
    level: str | None = Query(None),
    category: str | None = Query(None),
    session_id: str | None = Query(None),
    job_run_id: str | None = Query(None),
    event_name: str | None = Query(None),
    q: str | None = Query(None),
    since: str | None = Query(None),
    until: str | None = Query(None),
    limit: int = Query(200, ge=1, le=1000),
    offset: int = Query(0, ge=0),
    system: str | None = Query(None, description="'pead' or 'orb' to scope to one system"),
) -> dict[str, Any]:
    store = _get_store()
    rows, total = store.query(
        source=source, level=level, category=category,
        session_id=session_id, job_run_id=job_run_id, event_name=event_name,
        q=q, since=since, until=until,
        limit=limit, offset=offset,
        system=system,
    )
    next_offset = offset + limit if offset + limit < total else None
    return {"rows": rows, "total": total, "offset": offset, "next_offset": next_offset}


@router.get("/runs")
def list_runs(limit: int = Query(20, ge=1, le=100)) -> list[dict[str, Any]]:
    return _get_store().recent_runs(limit=limit)


@router.get("/sources")
def list_sources() -> list[str]:
    return _get_store().distinct_sources()


@router.delete("")
def purge_events(before: str = Query(..., description="ISO-8601 datetime; delete events older than this")) -> dict[str, Any]:
    deleted = _get_store().purge_before(before)
    return {"deleted": deleted}


# ── Health endpoint (mounted at /health to match plan, kept in events router) ──

health_router = APIRouter(tags=["health"])


@health_router.get("/health")
def get_health() -> dict[str, Any]:
    return _get_store().health_summary()
