"""cortex/api/routes/events.py — Event log endpoints."""

import json as _json
import logging
from typing import Any, Dict, List, Optional

from fastapi import APIRouter, Depends, HTTPException

from cortex.api.deps import PREFIX, plugin_holder, get_plugin

logger = logging.getLogger(__name__)

router = APIRouter()


def _make_routes(verify_api_key):
    """Register event routes with the given auth dependency."""

    @router.get(
        "/api/v1/events",
        summary="Browse event log",
        tags=["Events"],
    )
    async def list_events(
        owner_id: Optional[str] = None,
        event_type: Optional[str] = None,
        limit: int = 50,
        after: Optional[str] = None,
        _: None = Depends(verify_api_key),
    ):
        """Return events from the event_log table for *owner_id*."""
        plugin = plugin_holder.get("plugin")
        if plugin is None or plugin.storage is None:
            raise HTTPException(status_code=503, detail="Storage unavailable")

        owner_id = owner_id or getattr(plugin.config, "owner_id", "default")

        limit = max(1, min(int(limit), 500))

        try:
            rows = await plugin.storage.get_events(
                owner_id=owner_id,
                event_type=event_type,
                limit=limit,
                after=after,
            )
        except Exception as exc:
            logger.error("GET /api/v1/events error: %s", exc, exc_info=True)
            raise HTTPException(status_code=500, detail="Internal server error")

        events_out = []
        for row in rows:
            payload = None
            if row.get("payload_json"):
                try:
                    payload = _json.loads(row["payload_json"])
                except Exception:
                    payload = row["payload_json"]
            events_out.append(
                {
                    "id":         row["id"],
                    "owner_id":   row["owner_id"],
                    "event_type": row["event_type"],
                    "timestamp":  row["timestamp"],
                    "payload":    payload,
                    "session_id": row["session_id"],
                    "created_at": row["created_at"],
                }
            )

        return {"events": events_out, "count": len(events_out)}
