"""Lesson 5: a minimal in-memory vector store with cosine similarity and metadata filters."""
from __future__ import annotations

import json
from pathlib import Path

from .documents import Chunk


def dot(a: list[float], b: list[float]) -> float:
    return sum(x * y for x, y in zip(a, b))


class VectorStore:
    def __init__(self, embedder):
        self.embedder = embedder
        self.chunks: list[Chunk] = []
        self.vectors: list[list[float]] = []

    def add(self, chunks: list[Chunk]) -> None:
        self.vectors += self.embedder.embed([c.text for c in chunks])
        self.chunks += chunks

    def search(self, query: str, k: int = 5, where: dict | None = None) -> list[tuple[Chunk, float]]:
        """Brute-force cosine search (vectors are normalized, so dot product = cosine)."""
        q = self.embedder.embed([query])[0]
        hits = []
        for chunk, vec in zip(self.chunks, self.vectors):
            if where and any(chunk.metadata.get(key) != val for key, val in where.items()):
                continue
            hits.append((chunk, dot(q, vec)))
        hits.sort(key=lambda x: (-x[1], x[0].id))
        return hits[:k]

    def save(self, path: str | Path) -> None:
        payload = [{"id": c.id, "doc_id": c.doc_id, "text": c.text, "metadata": c.metadata, "vector": v}
                   for c, v in zip(self.chunks, self.vectors)]
        Path(path).write_text(json.dumps(payload), encoding="utf-8")

    def load(self, path: str | Path) -> None:
        for item in json.loads(Path(path).read_text(encoding="utf-8")):
            self.chunks.append(Chunk(item["id"], item["doc_id"], item["text"], item["metadata"]))
            self.vectors.append(item["vector"])
