"""Embed a set of passages in one batch, then search them by meaning.

  python -m pip install -U openai
  export GRIDLINE_TOKEN="gla_..."
  python embed_search.py

It creates one batch, charged to your prepaid credits.
"""

import json
import math
import os
import time

from openai import OpenAI

client = OpenAI(
    base_url="https://api.gridlinegpu.com/openai/v1",
    api_key=os.environ["GRIDLINE_TOKEN"],
    timeout=60,
)

MODEL = "qwen3-embedding-0.6b"
# Qwen3-Embedding embeds exactly the text you send: questions get an instruction in front,
# in the form its model card gives, and passages go bare.
TASK = "Given a customer question, retrieve the help article that answers it"

# --- 1. Gather the text ---
# Replace PASSAGES with your own: help articles, product descriptions, tickets, notes.

PASSAGES = [
    "To reset your password, choose Forgot password on the sign-in page and follow the email.",
    "Invoices are issued on the first day of each month and sent to the billing contact.",
    "You can change your plan at any time. The new price applies from the next billing day.",
    "Standard delivery takes three to five working days. Express delivery takes one.",
    "Returns are free within 30 days. Print a label from the Orders page.",
    "Two-step sign-in can be turned on under Settings, Security.",
    "The mobile app needs iOS 16 or Android 12, or later.",
    "Refunds go back to the original payment method within five working days.",
    "Team plans include shared folders and up to 50 members.",
    "To export your data, open Settings, Privacy, and choose Download my data.",
    "Our support team answers email between 9:00 and 18:00 UTC on weekdays.",
    "A damaged item can be replaced or refunded. Send a photo with your order number.",
    "You can pay by card or, on annual plans, by bank transfer.",
    "The API allows 600 requests a minute for each key.",
    "Closing your account deletes your data after 30 days.",
    "Orders can be sent to a new address until they leave the warehouse.",
]
QUESTIONS = [
    "how do I get my money back",
    "can I log in with a second factor",
    "what phones does the app run on",
]

# --- 2. Write the requests ---
# One line can carry up to 2,048 inputs, and one file up to 50,000 lines.

queries = [f"Instruct: {TASK}\nQuery:{question}" for question in QUESTIONS]
with open("requests.jsonl", "w") as out:
    for custom_id, texts in (("passages", PASSAGES), ("questions", queries)):
        line = {
            "custom_id": custom_id,
            "method": "POST",
            "url": "/v1/embeddings",
            "body": {"model": MODEL, "input": texts},
        }
        out.write(json.dumps(line) + "\n")

# --- 3. Run the batch ---

batch_input = client.files.create(file=open("requests.jsonl", "rb"), purpose="batch")
batch = client.batches.create(
    input_file_id=batch_input.id,
    endpoint="/v1/embeddings",
    completion_window="24h",
)
print(batch.id, batch.status)
while batch.status not in ("completed", "failed", "expired", "cancelled"):
    time.sleep(30)
    batch = client.batches.retrieve(batch.id)
if batch.status != "completed":
    raise SystemExit(f"{batch.id} ended {batch.status}: {batch.errors}")

# --- 4. Read the vectors ---
# Each result holds one embedding per input, with the input's position in "index".

vectors = {}
for line in client.files.content(batch.output_file_id).text.splitlines():
    row = json.loads(line)
    data = sorted(row["response"]["body"]["data"], key=lambda item: item["index"])
    vectors[row["custom_id"]] = [item["embedding"] for item in data]
print(len(vectors["passages"]), "passages,", len(vectors["passages"][0]), "dimensions each")

# --- 5. Search ---
# Cosine similarity in plain Python. Past a few thousand passages, use numpy or a vector store.


def cosine(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))


for question, vector in zip(QUESTIONS, vectors["questions"]):
    scores = [cosine(vector, passage) for passage in vectors["passages"]]
    best = sorted(range(len(PASSAGES)), key=lambda n: scores[n], reverse=True)[:2]
    print(question)
    for n in best:
        print(f"  {scores[n]:.3f}  {PASSAGES[n]}")
