"""Pattern: long-term memory store with keyword search.

SQLite gives you durable, queryable memory with zero infrastructure. FTS5 adds
BM25 keyword search. Vector search can be layered on later (store an embedding
column, or use an extension such as sqlite-vec); keyword search is a strong
baseline for names, IDs and exact terms that embeddings often miss.
"""
from __future__ import annotations

import json
import re
import sqlite3
import time
from dataclasses import dataclass, field

from .scoring import combined_score

SCHEMA = """
CREATE TABLE IF NOT EXISTS memories (
    id INTEGER PRIMARY KEY,
    kind TEXT NOT NULL DEFAULT 'fact',
    content TEXT NOT NULL,
    tags TEXT NOT NULL DEFAULT '[]',
    importance REAL NOT NULL DEFAULT 0.5,
    created_at REAL NOT NULL,
    last_accessed REAL NOT NULL,
    access_count INTEGER NOT NULL DEFAULT 0,
    source TEXT,
    namespace TEXT NOT NULL DEFAULT 'default'
);
CREATE INDEX IF NOT EXISTS memories_ns ON memories(namespace, created_at);
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
    content, content='memories', content_rowid='id', tokenize='porter unicode61'
);
CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN
    INSERT INTO memories_fts(rowid, content) VALUES (new.id, new.content);
END;
CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN
    INSERT INTO memories_fts(memories_fts, rowid, content) VALUES ('delete', old.id, old.content);
END;
CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE OF content ON memories BEGIN
    INSERT INTO memories_fts(memories_fts, rowid, content) VALUES ('delete', old.id, old.content);
    INSERT INTO memories_fts(rowid, content) VALUES (new.id, new.content);
END;
"""

_WORD = re.compile(r"\w+", re.UNICODE)
STOPWORDS = frozenset("""a an and are as at be but by can do does did for from has have how i in is it its
me my of on or our so that the their them then there these they this to was we were what when where which
who why will with you your""".split())


@dataclass
class Memory:
    id: int
    kind: str
    content: str
    tags: list[str] = field(default_factory=list)
    importance: float = 0.5
    created_at: float = 0.0
    last_accessed: float = 0.0
    access_count: int = 0
    source: str | None = None
    namespace: str = "default"
    score: float = 0.0


def fts_query(text: str) -> str:
    """Turn free text into a safe FTS5 query: quoted terms joined by OR."""
    terms = [t for t in _WORD.findall(text.lower()) if len(t) > 1 and t not in STOPWORDS]
    return " OR ".join(f'"{t}"' for t in dict.fromkeys(terms))


class MemoryStore:
    def __init__(self, path: str = ":memory:", clock=time.time):
        self.db = sqlite3.connect(path)
        self.db.row_factory = sqlite3.Row
        self.db.executescript(SCHEMA)
        self.clock = clock

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

    def add(self, content: str, *, kind: str = "fact", tags: list[str] | None = None,
            importance: float = 0.5, source: str | None = None, namespace: str = "default") -> int:
        if not content.strip():
            raise ValueError("content must not be empty")
        if not 0.0 <= importance <= 1.0:
            raise ValueError("importance must be between 0 and 1")
        now = self.clock()
        cur = self.db.execute(
            "INSERT INTO memories(kind, content, tags, importance, created_at, last_accessed, source, namespace)"
            " VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
            (kind, content.strip(), json.dumps(tags or []), importance, now, now, source, namespace),
        )
        self.db.commit()
        return int(cur.lastrowid)

    def _row(self, row: sqlite3.Row, score: float = 0.0) -> Memory:
        return Memory(id=row["id"], kind=row["kind"], content=row["content"], tags=json.loads(row["tags"]),
                      importance=row["importance"], created_at=row["created_at"],
                      last_accessed=row["last_accessed"], access_count=row["access_count"],
                      source=row["source"], namespace=row["namespace"], score=score)

    def get(self, memory_id: int) -> Memory | None:
        row = self.db.execute("SELECT * FROM memories WHERE id = ?", (memory_id,)).fetchone()
        return self._row(row) if row else None

    def update(self, memory_id: int, content: str) -> None:
        self.db.execute("UPDATE memories SET content = ? WHERE id = ?", (content.strip(), memory_id))
        self.db.commit()

    def forget(self, memory_id: int) -> bool:
        cur = self.db.execute("DELETE FROM memories WHERE id = ?", (memory_id,))
        self.db.commit()
        return cur.rowcount > 0

    def forget_namespace(self, namespace: str) -> int:
        """Delete everything for one user or tenant (right-to-be-forgotten)."""
        cur = self.db.execute("DELETE FROM memories WHERE namespace = ?", (namespace,))
        self.db.commit()
        return cur.rowcount

    def recent(self, n: int = 10, namespace: str = "default") -> list[Memory]:
        rows = self.db.execute(
            "SELECT * FROM memories WHERE namespace = ? ORDER BY created_at DESC, id DESC LIMIT ?",
            (namespace, n)).fetchall()
        return [self._row(r) for r in rows]

    def search(self, query: str, k: int = 5, *, namespace: str = "default", kind: str | None = None,
               half_life_days: float = 30.0, weights: tuple[float, float, float] = (1.0, 1.0, 1.0),
               touch: bool = True) -> list[Memory]:
        """Keyword search ranked by relevance, recency and importance.

        BM25 from FTS5 is negative (lower is better). We flip it and divide by the best
        score in the candidate set, so the top keyword match has relevance 1.0, then
        combine with recency and importance.
        """
        q = fts_query(query)
        if not q:
            return []
        sql = ("SELECT m.*, bm25(memories_fts) AS rank FROM memories_fts "
               "JOIN memories m ON m.id = memories_fts.rowid "
               "WHERE memories_fts MATCH ? AND m.namespace = ?")
        params: list = [q, namespace]
        if kind:
            sql += " AND m.kind = ?"
            params.append(kind)
        sql += " ORDER BY rank LIMIT ?"
        params.append(max(k * 5, 20))
        rows = self.db.execute(sql, params).fetchall()
        if not rows:
            return []
        raw = [-r["rank"] for r in rows]
        best = max(raw) or 1.0
        now = self.clock()
        scored = []
        for r, rel in zip(rows, raw):
            relevance = max(0.0, rel / best)
            s = combined_score(relevance=relevance, last_accessed=r["last_accessed"], importance=r["importance"],
                               now=now, half_life_days=half_life_days, weights=weights)
            scored.append(self._row(r, s))
        scored.sort(key=lambda m: m.score, reverse=True)
        top = scored[:k]
        if touch and top:
            self.db.executemany(
                "UPDATE memories SET last_accessed = ?, access_count = access_count + 1 WHERE id = ?",
                [(now, m.id) for m in top])
            self.db.commit()
        return top

    def prune(self, *, older_than_days: float, max_importance: float = 0.3, namespace: str = "default") -> int:
        """Forget low-importance memories nobody has used for a long time."""
        cutoff = self.clock() - older_than_days * 86400
        cur = self.db.execute(
            "DELETE FROM memories WHERE namespace = ? AND last_accessed < ? AND importance <= ?",
            (namespace, cutoff, max_importance))
        self.db.commit()
        return cur.rowcount
