"""Crawler event repository — warehouse-only persistence."""

from __future__ import annotations
from typing import Any

from repo_core import BaseRepository

from .model import CrawlerEvent


class CrawlerEventRepository(BaseRepository[CrawlerEvent]):
    """Repository for persisting crawler lifecycle events into Doris.

    Warehouse-only — no database or search backends.  Events are
    write-once (insert-only) and never upserted.

    Usage::

        repo = CrawlerEventRepository(model=CrawlerEvent)
        async with repo:
            await repo.warehouse_insert_one(TABLE, event.to_warehouse())
    """

    TABLE = "telegram_crawler_events"
    _backends = {"doris"}

    # -- Convenience wrappers ----------------------------------------------

    async def dw_create_event(self, instance: CrawlerEvent) -> CrawlerEvent:
        """Insert an event row into the warehouse."""
        return await self.warehouse_insert_one(
            self.TABLE,
            instance.to_warehouse(),
            returning=["*"],
        )

    async def dw_find_by_account(
        self, account_id: str, *, limit: int = 100
    ) -> list[CrawlerEvent]:
        """Return recent events for a specific account."""
        return await self.warehouse_find(
            self.TABLE,
            {"account_id": account_id},
            limit=limit,
            order_by=["-created_at"],
        )

    async def dw_recent_events(
        self,
        *,
        limit: int = 100,
        account_id: str | None = None,
        event_type: str | None = None,
    ) -> list[CrawlerEvent]:
        """Return recent events with optional filtering.

        Args:
            limit: Max rows to return.
            account_id: Optional filter by account UUID.
            event_type: Optional filter by event type
                (``connect``, ``disconnect``, ``auth_error``, …).

        Returns:
            List of event dicts ordered by ``created_at DESC``.
        """
        conditions: dict[str, Any] = {}
        if account_id is not None:
            conditions["account_id"] = account_id
        if event_type is not None:
            conditions["event_type"] = event_type

        return await self.warehouse_find(
            self.TABLE,
            conditions,
            limit=limit,
            order_by=["-created_at"],
        )

    async def dw_event_summary(self, *, days: int = 7) -> list[dict[str, Any]]:
        """Count of events by type over the last N days.

        Returns rows like:
        ``{"event_type": "connect", "count": 45}``,
        ``{"event_type": "disconnect", "count": 42}``, …
        """
        return await (
            self.warehouse_table(self.TABLE)
            .select("event_type", "COUNT(*) AS count")
            .where_raw(
                "created_at",
                ">= DATE_SUB(NOW(), INTERVAL :days DAY)",
                {"days": days},
            )
            .group_by("event_type")
            .order_by("-count")
            .all()
        )
