"""
Simple CLI to query FAISS index and print top-k passages.
"""
import faiss, json, numpy as np
from sentence_transformers import SentenceTransformer
from pathlib import Path

INDEX = Path("vector.index")
CHUNKS = Path("chunks.jsonl")
MODEL_NAME = "distiluse-base-multilingual-cased-v1"

model = SentenceTransformer(MODEL_NAME)
index = faiss.read_index(str(INDEX))

chunks = [json.loads(l) for l in CHUNKS.read_text(encoding="utf-8").splitlines() if l.strip()]
texts = [c["text"] for c in chunks]

def query(q, k=5):
    emb = model.encode([q], convert_to_numpy=True)
    faiss.normalize_L2(emb)
    D, I = index.search(emb, k)
    for score, idx in zip(D[0], I[0]):
        print(f"score={float(score):.4f}")
        print(texts[idx])
        print("-"*80)

if __name__ == "__main__":
    import sys
    q = " ".join(sys.argv[1:]) if len(sys.argv)>1 else input("Masukkan pertanyaan: ")
    query(q, k=5)
