"""cortex/storage/queries/event_queries.py — Event log storage mixin."""

import datetime
from typing import Any, Dict, List, Optional


class EventQueryMixin:
    """Mixin providing eventquery methods."""

    async def log_event(
        self,
        event_type: str,
        owner_id: str = "default",
        timestamp: Optional[str] = None,
        payload_json: Optional[str] = None,
        session_id: Optional[str] = None,
    ) -> str:
        """Insert a row into event_log and return its generated id.

        Parameters
        ----------
        event_type:
            String representation of the EventType (e.g. ``"memory.created"``).
        owner_id:
            Owner/user scope for this event.
        timestamp:
            ISO-8601 UTC string. Defaults to ``datetime('now')`` in SQLite.
        payload_json:
            JSON-encoded payload dict, or None.
        session_id:
            Optional session association.

        Returns
        -------
        The generated UUID-like row id.
        """
        import uuid as _uuid
        row_id = _uuid.uuid4().hex
        ts = timestamp or __import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat()
        async with self._write_lock:
            conn = await self._get_conn()
            await conn.execute(
                """
                INSERT INTO event_log (id, owner_id, event_type, timestamp, payload_json, session_id)
                VALUES (?, ?, ?, ?, ?, ?)
                """,
                (row_id, owner_id, event_type, ts, payload_json, session_id),
            )
            await conn.commit()
            return row_id


    async def get_events(
        self,
        owner_id: str = "default",
        event_type: Optional[str] = None,
        limit: int = 50,
        after: Optional[str] = None,
    ) -> list:
        """Return events for *owner_id*, newest-first.

        Parameters
        ----------
        owner_id:
            Filter to this owner scope.
        event_type:
            Optional event type string filter (exact match).
        limit:
            Maximum number of rows to return (capped at 500).
        after:
            ISO-8601 timestamp cursor — return only events *after* this time
            (exclusive, i.e. ``timestamp > after``).

        Returns
        -------
        List of dicts with keys: id, owner_id, event_type, timestamp,
        payload_json, session_id, created_at.
        """
        limit = min(int(limit), 500)
        params: list = [owner_id]
        where_clauses = ["owner_id = ?"]

        if event_type:
            where_clauses.append("event_type = ?")
            params.append(event_type)

        if after:
            where_clauses.append("timestamp > ?")
            params.append(after)

        where_sql = " AND ".join(where_clauses)
        params.append(limit)

        conn = await self._get_conn()
        async with conn.execute(
            f"""
            SELECT id, owner_id, event_type, timestamp, payload_json, session_id, created_at
            FROM event_log
            WHERE {where_sql}
            ORDER BY timestamp DESC
            LIMIT ?
            """,
            params,
        ) as cur:
            rows = await cur.fetchall()

        return [
            {
                "id":           r[0],
                "owner_id":     r[1],
                "event_type":   r[2],
                "timestamp":    r[3],
                "payload_json": r[4],
                "session_id":   r[5],
                "created_at":   r[6],
            }
            for r in rows
        ]

    async def prune_old_logs(self, retention_days: int = 90) -> Dict[str, int]:
        """Delete event_log and request_log rows older than *retention_days*.

        This implements TTL/rotation for the operational log tables (L3 audit fix).
        Safe to call from the circadian cycle or as an admin maintenance operation.

        Parameters
        ----------
        retention_days:
            Number of days to retain log entries. Rows with ``created_at``
            older than ``now - retention_days`` are permanently deleted.
            Defaults to 90 days.

        Returns
        -------
        Dict with keys ``event_log`` and ``request_log`` containing the number
        of rows deleted from each table.
        """
        cutoff = (
            datetime.datetime.now(datetime.timezone.utc)
            - datetime.timedelta(days=int(retention_days))
        ).isoformat()

        async with self._write_lock:
            conn = await self._get_conn()

            async with conn.execute(
                "DELETE FROM event_log WHERE created_at < ?", (cutoff,)
            ) as cur:
                event_count = cur.rowcount

            async with conn.execute(
                "DELETE FROM request_log WHERE created_at < ?", (cutoff,)
            ) as cur:
                request_count = cur.rowcount

            await conn.commit()

        return {"event_log": event_count, "request_log": request_count}
