"""Tier mémoire local : journal de conversation en SQLite (brut, gitignoré).

Phase 1 : on persiste juste les tours de conversation. La distillation vers GitHub
et l'embedding Qdrant (s01) arrivent en phase 4.
"""

from __future__ import annotations

import sqlite3
import time
from pathlib import Path


class LocalMemory:
    def __init__(self, db_path: str):
        self.path = Path(db_path).expanduser()
        self.path.parent.mkdir(parents=True, exist_ok=True)
        self._db = sqlite3.connect(str(self.path), check_same_thread=False)
        self._db.execute(
            """CREATE TABLE IF NOT EXISTS turns (
                   id        INTEGER PRIMARY KEY AUTOINCREMENT,
                   ts        REAL NOT NULL,
                   role      TEXT NOT NULL,
                   content   TEXT NOT NULL,
                   mode      TEXT
               )"""
        )
        self._db.commit()

    def log(self, role: str, content: str, mode: str | None = None) -> None:
        self._db.execute(
            "INSERT INTO turns (ts, role, content, mode) VALUES (?, ?, ?, ?)",
            (time.time(), role, content, mode),
        )
        self._db.commit()

    def recent(self, limit: int = 20) -> list[dict]:
        cur = self._db.execute(
            "SELECT ts, role, content, mode FROM turns ORDER BY id DESC LIMIT ?",
            (limit,),
        )
        rows = [
            {"ts": ts, "role": role, "content": content, "mode": mode}
            for ts, role, content, mode in cur.fetchall()
        ]
        return list(reversed(rows))

    def close(self) -> None:
        self._db.close()
