import sqlite3
import uuid
from datetime import datetime


class SQLiteManager:
    def __init__(self, db_path=":memory:"):
        self.connection = sqlite3.connect(db_path, check_same_thread=False)
        self._create_history_table()

    def _create_history_table(self):
        with self.connection:
            self.connection.execute(
                """
                CREATE TABLE IF NOT EXISTS history (
                    id TEXT PRIMARY KEY,
                    memory_id TEXT,
                    old_memory TEXT,
                    new_memory TEXT,
                    event TEXT,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    is_deleted INTEGER
                )
            """
            )
            self.connection.execute(
                """
                CREATE INDEX IF NOT EXISTS idx_history ON history("id")
            """
            )

    def add_history(
        self,
        memory_id,
        old_memory,
        new_memory,
        event,
        created_at=None,
        updated_at=None,
        is_deleted=0,
    ):
        with self.connection:
            self.connection.execute(
                """
                INSERT INTO history (id, memory_id, old_memory, new_memory, event, created_at, updated_at, is_deleted)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            """,
                (
                    str(uuid.uuid4()),
                    memory_id,
                    old_memory,
                    new_memory,
                    event,
                    created_at or datetime.now(),
                    updated_at or datetime.now(),
                    is_deleted,
                ),
            )

    def get_history(self, memory_id):
        cursor = self.connection.execute(
            """
            SELECT id, memory_id, old_memory, new_memory, event, created_at, updated_at
            FROM history
            WHERE memory_id = ?
            ORDER BY updated_at ASC
        """,
            (memory_id,),
        )
        rows = cursor.fetchall()
        return [
            {
                "id": row[0],
                "memory_id": row[1],
                "old_memory": row[2],
                "new_memory": row[3],
                "event": row[4],
                "created_at": row[5],
                "updated_at": row[6],
            }
            for row in rows
        ]

    def reset(self):
        with self.connection:
            self.connection.execute("DROP INDEX IF EXISTS idx_history")
            self.connection.execute("DROP TABLE IF EXISTS history")
            self._create_history_table()
