"""Persistent AI memory storage."""

from __future__ import annotations

import json

from bot.infra.db.manager import db_manager


class MemoryRepository:
    async def ensure_schema(self) -> None:
        await db_manager.execute(
            """
            CREATE TABLE IF NOT EXISTS ai_memory (
                chat_id INTEGER NOT NULL,
                user_id INTEGER NOT NULL,
                payload TEXT NOT NULL,
                updated_at INTEGER NOT NULL,
                PRIMARY KEY(chat_id, user_id)
            )
            """
        )

        await db_manager.execute(
            """
            CREATE TABLE IF NOT EXISTS ai_memory_events (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                chat_id INTEGER NOT NULL,
                user_id INTEGER NOT NULL,
                event_type TEXT NOT NULL,
                content TEXT NOT NULL,
                created_at INTEGER NOT NULL
            )
            """
        )

    async def save_memory(self, chat_id: int, user_id: int, payload: dict) -> None:
        await db_manager.execute(
            """
            INSERT OR REPLACE INTO ai_memory
            (chat_id, user_id, payload, updated_at)
            VALUES (?, ?, ?, strftime('%s','now'))
            """,
            (chat_id, user_id, json.dumps(payload, ensure_ascii=False)),
        )

    async def load_memory(self, chat_id: int, user_id: int) -> dict | None:
        row = await db_manager.fetchone(
            "SELECT payload FROM ai_memory WHERE chat_id=? AND user_id=?",
            (chat_id, user_id),
        )

        if not row:
            return None

        raw = row[0] if not isinstance(row, dict) else row["payload"]

        return json.loads(raw)

    async def add_memory_event(
        self,
        chat_id: int,
        user_id: int,
        event_type: str,
        content: str,
    ) -> None:
        await db_manager.execute(
            """
            INSERT INTO ai_memory_events
            (chat_id, user_id, event_type, content, created_at)
            VALUES (?, ?, ?, ?, strftime('%s','now'))
            """,
            (chat_id, user_id, event_type, content[:500]),
        )

    async def recent_events(self, chat_id: int, user_id: int, limit: int = 5) -> list:
        return await db_manager.fetchall(
            """
            SELECT event_type, content
            FROM ai_memory_events
            WHERE chat_id=? AND user_id=?
            ORDER BY id DESC
            LIMIT ?
            """,
            (chat_id, user_id, limit),
        )


memory_repository = MemoryRepository()
