import faiss
import numpy as np
import time


class VectorStore:
    def __init__(self, dim=384):
        self.index= faiss.IndexFlatIP(dim)
        self.data= []  # stores (query, answer)

    def add(self, embedding, query, answer):
        embedding= np.array([embedding]).astype("float32")
        self.index.add(embedding)

        self.data.append({
            "query": query,
            "answer": answer,
            "timestamp": time.time()
        })

    def search(self, embedding, k=3):
        if len(self.data) == 0:
            return []

        embedding= np.array([embedding]).astype("float32")
        D, I = self.index.search(embedding, k=k)

        results= []
        for i in range(k):
            idx= I[0][i]

            if idx == -1 or idx >= len(self.data):
                continue

            sim= D[0][i]
            results.append((sim, self.data[idx]))

        return results