"""Recent activity events — read-only feed for the UI background-work toaster.

The UI polls this endpoint every ~8s with the timestamp of the last event
it has already shown, and renders a toast for each new event. Filtered to
medium+ importance by default so users only see things worth surfacing.
"""

from __future__ import annotations

import logging

from fastapi import APIRouter, Request

log = logging.getLogger(__name__)

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


@router.get("/recent")
async def recent_events(
    request: Request,
    since: str | None = None,
    categories: str | None = None,
    min_importance: str = "medium",
    limit: int = 50,
) -> dict:
    """Return events newer than ``since`` (ISO timestamp), optionally filtered
    by comma-separated categories.

    Cheap, read-only, in-memory query — safe to poll. Returns ``{events: [], now: iso}``.
    The ``now`` echo gives the client a server-side timestamp to use as the
    next ``since`` value, avoiding clock-skew bugs.
    """
    activity = getattr(request.app.state, "activity_logger", None)
    from datetime import UTC, datetime

    from agntspace.infra.timezone import format_iso_local

    now = format_iso_local(datetime.now(UTC))
    if not activity:
        return {"events": [], "now": now}

    cat_list = [c.strip() for c in categories.split(",")] if categories else None
    try:
        events = activity.get_recent_events(
            since_iso=since,
            categories=cat_list,
            min_importance=min_importance,
            limit=max(1, min(limit, 200)),
        )
    except Exception:
        log.exception("recent_events query failed")
        return {"events": [], "now": now}

    return {
        "events": [
            {
                "category": e.category,
                "action": e.action,
                "summary": e.summary,
                "details": e.details,
                "timestamp": e.timestamp,
                "importance": e.importance,
                "correlation_id": e.correlation_id,
            }
            for e in events
        ],
        "now": now,
    }
