"""Embed the RAG chunks and build a FAISS index.

    python scripts/build_index.py --config config/config.yaml

Reads data/kb/chunks.jsonl (from prepare_data.py), embeds each chunk with the small embedder,
and writes:
  - data/kb/index.faiss       (inner-product index over L2-normalized vectors == cosine)
  - data/kb/index.meta.json   (parallel list of {text, source})
"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))

from agent.embeddings import Embedder  # noqa: E402
from agent.settings import load_config  # noqa: E402


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--config", default="config/config.yaml")
    args = ap.parse_args()
    cfg = load_config(args.config)

    import faiss

    kb_dir = cfg.resolve("data.kb_dir")
    chunks_path = kb_dir / "chunks.jsonl"
    if not chunks_path.exists():
        raise SystemExit(f"{chunks_path} not found. Run scripts/prepare_data.py first.")

    meta = [json.loads(line) for line in chunks_path.read_text(encoding="utf-8").splitlines() if line.strip()]
    if not meta:
        raise SystemExit("No chunks to index. Add KB documents to data/raw/ and re-run prepare_data.")

    embedder = Embedder(cfg)
    vecs = embedder.embed_documents([m["text"] for m in meta])  # (N, D), normalized

    index = faiss.IndexFlatIP(vecs.shape[1])
    index.add(vecs)

    faiss.write_index(index, str(kb_dir / "index.faiss"))
    (kb_dir / "index.meta.json").write_text(json.dumps(meta, ensure_ascii=False), encoding="utf-8")

    print(f"Indexed {len(meta)} chunks (dim={vecs.shape[1]}) -> {kb_dir / 'index.faiss'}")


if __name__ == "__main__":
    main()
