"""cortex/storage/queries/stats_queries.py — Dashboard/stats storage mixin."""

from typing import Any, Dict, List, Optional


class StatsQueryMixin:
    """Mixin providing statsquery methods."""

    async def get_dashboard_stats(self, owner_id: str = "default") -> dict:
        """
        Return a comprehensive dashboard stats dict in one round-trip each.

        Keys returned:
            total_memories, active_count, cooling_count, deprecated_count,
            total_entities, total_sessions, total_cornerstones,
            avg_drift_score, category_counts, memory_type_counts, status_counts
        """
        conn = await self._get_conn()

        # -- Claim aggregate counts by status --
        async with conn.execute(
            """
            SELECT
                COUNT(*)                                               AS total,
                SUM(CASE WHEN status='active'     THEN 1 ELSE 0 END)  AS active,
                SUM(CASE WHEN status='cooling'    THEN 1 ELSE 0 END)  AS cooling,
                SUM(CASE WHEN status='deprecated' THEN 1 ELSE 0 END)  AS deprecated
            FROM semantic_claim
            WHERE owner_id = ?
            """,
            (owner_id,),
        ) as cur:
            row = await cur.fetchone()

        total_memories  = row[0] or 0
        active_count    = row[1] or 0
        cooling_count   = row[2] or 0
        deprecated_count = row[3] or 0

        # -- Entity count --
        async with conn.execute(
            "SELECT COUNT(*) FROM entity WHERE owner_id = ?", (owner_id,)
        ) as cur:
            ent_row = await cur.fetchone()
        total_entities = ent_row[0] if ent_row else 0

        # -- Session count --
        async with conn.execute(
            "SELECT COUNT(*) FROM session_record WHERE owner_id = ?", (owner_id,)
        ) as cur:
            sess_row = await cur.fetchone()
        total_sessions = sess_row[0] if sess_row else 0

        # -- Cornerstone count + avg drift score --
        async with conn.execute(
            """
            SELECT COUNT(*), AVG(drift_score)
            FROM cornerstone_memory
            WHERE owner_id = ? AND status != 'retired'
            """,
            (owner_id,),
        ) as cur:
            cs_row = await cur.fetchone()
        total_cornerstones = cs_row[0] if cs_row else 0
        avg_drift_score    = round(cs_row[1] or 0.0, 4) if cs_row else 0.0

        # -- Category breakdown --
        async with conn.execute(
            """
            SELECT category, COUNT(*) AS cnt
            FROM semantic_claim
            WHERE owner_id = ?
            GROUP BY category
            ORDER BY cnt DESC
            """,
            (owner_id,),
        ) as cur:
            cat_rows = await cur.fetchall()
        category_counts = {r[0]: r[1] for r in cat_rows}

        # -- Memory type breakdown --
        async with conn.execute(
            """
            SELECT memory_type, COUNT(*) AS cnt
            FROM semantic_claim
            WHERE owner_id = ?
            GROUP BY memory_type
            ORDER BY cnt DESC
            """,
            (owner_id,),
        ) as cur:
            type_rows = await cur.fetchall()
        memory_type_counts = {r[0]: r[1] for r in type_rows}

        # -- Status breakdown (all statuses) --
        async with conn.execute(
            """
            SELECT status, COUNT(*) AS cnt
            FROM semantic_claim
            WHERE owner_id = ?
            GROUP BY status
            ORDER BY cnt DESC
            """,
            (owner_id,),
        ) as cur:
            status_rows = await cur.fetchall()
        status_counts = {r[0]: r[1] for r in status_rows}

        return {
            "total_memories":    total_memories,
            "active_count":      active_count,
            "cooling_count":     cooling_count,
            "deprecated_count":  deprecated_count,
            "total_entities":    total_entities,
            "total_sessions":    total_sessions,
            "total_cornerstones": total_cornerstones,
            "avg_drift_score":   avg_drift_score,
            "category_counts":   category_counts,
            "memory_type_counts": memory_type_counts,
            "status_counts":     status_counts,
        }


    async def get_request_stats(
        self,
        owner_id: str = "default",
        time_range: str = "7d",
        granularity: str = "day",
    ) -> list:
        """
        Return time-series request activity from request_log.

        Parameters
        ----------
        time_range  : '1d' | '7d' | '30d'
        granularity : 'hour' | 'day'

        Returns a list of {timestamp, count, request_type} dicts.
        """
        import json as _json

        days = {"1d": 1, "7d": 7, "30d": 30}.get(time_range, 7)
        cutoff = f"datetime('now', '-{days} days')"

        if granularity == "hour":
            trunc = "strftime('%Y-%m-%dT%H:00:00', created_at)"
        else:
            trunc = "strftime('%Y-%m-%d', created_at)"

        conn = await self._get_conn()
        async with conn.execute(
            f"""
            SELECT {trunc} AS ts,
                   request_type,
                   COUNT(*) AS cnt
            FROM request_log
            WHERE owner_id = ?
              AND created_at >= {cutoff}
            GROUP BY ts, request_type
            ORDER BY ts ASC, request_type ASC
            """,
            (owner_id,),
        ) as cur:
            rows = await cur.fetchall()

        return [
            {"timestamp": r[0], "request_type": r[1], "count": r[2]}
            for r in rows
        ]


    async def get_memory_stats(
        self,
        owner_id: str = "default",
        time_range: str = "30d",
    ) -> list:
        """
        Return daily memory-count time series from semantic_claim.created_at.

        Returns a list of {timestamp, count} dicts (cumulative per day).
        """
        days = {"1d": 1, "7d": 7, "30d": 30}.get(time_range, 30)
        cutoff = f"datetime('now', '-{days} days')"

        conn = await self._get_conn()
        async with conn.execute(
            f"""
            SELECT strftime('%Y-%m-%d', created_at) AS day,
                   COUNT(*) AS cnt
            FROM semantic_claim
            WHERE owner_id = ?
              AND created_at >= {cutoff}
            GROUP BY day
            ORDER BY day ASC
            """,
            (owner_id,),
        ) as cur:
            rows = await cur.fetchall()

        return [{"timestamp": r[0], "count": r[1]} for r in rows]


