"""Compare ANN recall against exact search on synthetic normalized vectors.

Install: python -m pip install numpy faiss-cpu
This is a teaching experiment, not a production latency benchmark.
"""
import time

import faiss
import numpy as np


def build(index, vectors, label):
    start = time.perf_counter()
    if not index.is_trained:
        index.train(vectors)
    index.add(vectors)
    print(f"{label}: train+add={time.perf_counter() - start:.3f}s")
    return index


def evaluate(index, queries, truth, label):
    index.search(queries, truth.shape[1])
    start = time.perf_counter()
    for _ in range(5):
        _, found = index.search(queries, truth.shape[1])
    elapsed = (time.perf_counter() - start) / 5
    recall = np.mean([
        len(set(a) & set(b)) / len(b)
        for a, b in zip(found, truth)
    ])
    print(f"{label}: recall@10={recall:.3f}, "
          f"batch_ms/query={elapsed * 1000 / len(queries):.3f}")


def main():
    faiss.omp_set_num_threads(4)
    print(f"Faiss {faiss.__version__}, NumPy {np.__version__}, threads=4")
    rng = np.random.default_rng(42)
    xb = rng.normal(size=(20_000, 64)).astype("float32")
    xq = rng.normal(size=(100, 64)).astype("float32")
    faiss.normalize_L2(xb)
    faiss.normalize_L2(xq)
    exact = build(faiss.IndexFlatIP(64), xb, "Flat")
    _, truth = exact.search(xq, 10)
    evaluate(exact, xq, truth, "Flat")

    hnsw = faiss.IndexHNSWFlat(64, 16, faiss.METRIC_INNER_PRODUCT)
    hnsw.hnsw.efConstruction = 80
    build(hnsw, xb, "HNSW")
    for ef in (16, 32, 64, 128):
        hnsw.hnsw.efSearch = ef
        evaluate(hnsw, xq, truth, f"HNSW efSearch={ef}")

    quantizer = faiss.IndexFlatIP(64)
    ivf = faiss.IndexIVFFlat(quantizer, 64, 128, faiss.METRIC_INNER_PRODUCT)
    build(ivf, xb, "IVF_FLAT")
    for nprobe in (1, 4, 16, 64, 128):
        ivf.nprobe = nprobe
        evaluate(ivf, xq, truth, f"IVF nprobe={nprobe}")


if __name__ == "__main__":
    main()
