import json

from .base import BaseMemoryRepo


class MemoryRepo(BaseMemoryRepo):
    TABLE = "memories"
    VEC_TABLE = "vec_memories"
    TAG_TABLE = "memory_tags"

    def get_tag_counts(self, project_dir: str | None = None) -> dict[str, int]:
        sql = f"SELECT tag, COUNT(*) as count FROM {self.TAG_TABLE} mt JOIN {self.TABLE} m ON mt.memory_id = m.id"
        params = []
        if project_dir is not None:
            sql += " WHERE m.project_dir=?"
            params.append(project_dir)
        sql += " GROUP BY tag ORDER BY count DESC"
        return {row["tag"]: row["count"] for row in self.conn.execute(sql, params).fetchall()}

    def get_ids_with_tag(self, tag: str, project_dir: str | None = None) -> list[dict]:
        sql = f"SELECT m.id, m.tags FROM {self.TABLE} m JOIN {self.TAG_TABLE} mt ON m.id = mt.memory_id WHERE mt.tag=?"
        params: list = [tag]
        if project_dir is not None:
            sql += " AND m.project_dir=?"
            params.append(project_dir)
        return [dict(r) for r in self.conn.execute(sql, params).fetchall()]
