"""Embed five articles locally, search Skeg, then remove this run's data."""

import argparse
import json
import math
import struct
import sys
import uuid
from urllib.request import Request, urlopen


ARTICLES = [
    ("Reset your password", "Use the password reset link to choose a new password."),
    ("Recover account access", "If you cannot sign in, request an account recovery email."),
    ("Download an invoice", "Open Billing, select a payment and download its invoice."),
    ("Change your plan", "Open Subscription to upgrade or downgrade your plan."),
    ("Invite a teammate", "Open Members and send an invitation to a colleague's email."),
]
MODEL = "embeddinggemma"


def embed(texts):
    request = Request(
        "http://127.0.0.1:11434/api/embed",
        data=json.dumps({"model": MODEL, "input": texts, "truncate": False}).encode(),
        headers={"Content-Type": "application/json"},
    )
    with urlopen(request, timeout=120) as response:
        vectors = json.load(response)["embeddings"]
    if len(vectors) != len(texts):
        raise ValueError("Ollama returned a different number of embeddings")
    dimension = len(vectors[0])
    if not dimension:
        raise ValueError("Ollama returned an empty vector")
    for values in vectors:
        if len(values) != dimension or not all(math.isfinite(v) for v in values):
            raise ValueError("Embeddings must have equal dimensions and finite values")
        if not any(v != 0 for v in values):
            raise ValueError("An embedding has zero norm")
    return [struct.pack("<" + "f" * dimension, *v) for v in vectors], dimension


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--query", default="I forgot my login details. How can I get back in?")
    args = parser.parse_args()

    import redis
    from redis.backoff import NoBackoff
    from redis.retry import Retry

    # Generate both documents and query before creating any Skeg records.
    texts = [f"title: {title} | text: {body}" for title, body in ARTICLES]
    query = f"task: search result | query: {args.query}"
    vectors, dimension = embed(texts + [query])
    index = "semantic_demo_" + uuid.uuid4().hex
    keys = [f"{index}:article:{i}" for i in range(1, len(ARTICLES) + 1)]
    client = redis.Redis(
        host="127.0.0.1", port=6388, protocol=3, decode_responses=False,
        socket_connect_timeout=5, socket_timeout=30,
        retry=Retry(NoBackoff(), 0),
    )
    print(f"Index: {index}; model: {MODEL}; dimension: {dimension}", flush=True)
    try:
        client.execute_command(
            "SKEG.VINDEX.CREATE", index, dimension, "KIND", "f32",
            "BACKEND", "flat", "PERSISTENCE", "ephemeral",
        )
        for row_id, ((title, body), key, vector) in enumerate(
            zip(ARTICLES, keys, vectors[:-1]), start=1,
        ):
            client.set(key, json.dumps({"title": title, "body": body}))
            client.execute_command("SKEG.VSET", index, row_id, vector)

        hits = client.execute_command("SKEG.VSEARCH", index, 3, 0, vectors[-1])
        print(f"Question: {args.query}")
        for offset in range(0, len(hits), 2):
            row_id, score = hits[offset:offset + 2]
            row_id = int(row_id)
            if not 1 <= row_id <= len(keys):
                raise ValueError(f"Unexpected row ID: {row_id}")
            raw = client.get(keys[row_id - 1])
            if raw is None:
                raise ValueError(f"Missing article for row {row_id}")
            article = json.loads(raw)
            print(f"{row_id}: {float(score):.4f} — {article['title']}")
            print(f"   {article['body']}")

        # The index and application KV records have separate lifecycles.
        client.execute_command("SKEG.VINDEX.DROP", index)
        for key in keys:
            client.delete(key)
        print("Removed this run's index and article records.")
    except Exception:
        print(
            "The run stopped; partial data may remain. No automatic retry was made.\n"
            f"Inspect index {index!r} and keys {index}:article:1 through :5.\n"
            "Use the tutorial's cleanup commands for these names.",
            file=sys.stderr,
        )
        raise
    finally:
        client.close()


if __name__ == "__main__":
    main()
