import os
import struct

import redis

port = int(os.environ.get("SKEG_LEARN_PORT", "6379"))
client = redis.Redis(
    host="127.0.0.1", port=port, protocol=3, decode_responses=False
)
index = "learn_search"


def vector(values):
    return struct.pack("<" + "f" * len(values), *values)


client.execute_command(
    "SKEG.VINDEX.CREATE", index, 4, "KIND", "tq2", "BACKEND", "disk",
    "PERSISTENCE", "durable", "IFNOTEXISTS",
)

articles = [
    (1, "Reset your password", [1.0, 0.0, 0.0, 0.0]),
    (2, "Download an invoice", [0.0, 1.0, 0.0, 0.0]),
    (3, "Recover account access", [0.8, 0.6, 0.0, 0.0]),
]
for row_id, title, coordinates in articles:
    client.set(f"article:{row_id}:title", title)
    client.execute_command("SKEG.VSET", index, row_id, vector(coordinates))

query = vector([1.0, 0.0, 0.0, 0.0])
hits = client.execute_command("SKEG.VSEARCH", index, 2, 100, query)

for offset in range(0, len(hits), 2):
    row_id, score = hits[offset:offset + 2]
    title = client.get(f"article:{int(row_id)}:title")
    print(f"{int(row_id)} {float(score):.3f} {title.decode('utf-8')}")
