import json
import os
from pathlib import Path

CHUNKS = Path(os.environ.get("CHUNKS_PATH", "chunks.jsonl"))  # shared pipeline file, not in this repo
COLLECTION = "docs"
OLLAMA = "http://localhost:11434/api/embed"


def read_chunks(path=CHUNKS):
    rows = [json.loads(line) for line in open(path)]
    models = {r["model"] for r in rows}
    dims = {r["dim"] for r in rows}
    assert len(models) == 1 and len(dims) == 1, (models, dims)
    return rows, models.pop(), dims.pop()


def section_of(url):
    """First path segment after /docs: /docs/guides/filters -> guides, /docs -> root."""
    rest = url.split("/docs", 1)[1].strip("/")
    return rest.split("/")[0] if rest else "root"


def embed_query(text, model):
    import requests
    # nomic-embed-text needs the search_query prefix at query time
    r = requests.post(OLLAMA, json={"model": model, "input": "search_query: " + text}, timeout=60)
    r.raise_for_status()
    return r.json()["embeddings"][0]
