import struct

import redis

client = redis.Redis(host="127.0.0.1", port=6383, protocol=3, decode_responses=False)
index = "learn_filters"


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


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

rows = [
    (1, [1.0, 0.0, 0.0, 0.0], b"lang=en year=2025 tag=guide"),
    (2, [0.96, 0.28, 0.0, 0.0], b"lang=it year=2023 tag=guide"),
    (3, [0.8, 0.6, 0.0, 0.0], b"lang=it year=2025 tag=guide"),
    (4, [0.6, 0.8, 0.0, 0.0], b"lang=it year=2024 tag=api"),
]
for row_id, coordinates, payload in rows:
    client.execute_command(
        "SKEG.VSET", index, row_id, vector(coordinates), "PAYLOAD", payload,
    )

query = vector([1.0, 0.0, 0.0, 0.0])
unfiltered = client.execute_command("SKEG.VSEARCH", index, 2, 100, query)
if [int(row_id) for row_id in unfiltered[::2]] != [1, 2]:
    raise RuntimeError(f"Unexpected unfiltered hits: {unfiltered!r}")

expression = "lang = it AND year >= 2024"
hits = client.execute_command(
    "SKEG.VSEARCH", index, 2, 100, query,
    "WITHPAYLOAD", "FILTER", expression,
)

if len(hits) != 6:
    raise RuntimeError(f"Expected two hits, got {hits!r}")

results = [
    (int(row_id), float(score), payload)
    for row_id, score, payload in zip(hits[::3], hits[1::3], hits[2::3])
]
expected = [(row_id, payload) for row_id, _, payload in rows[2:]]
if [(row_id, payload) for row_id, _, payload in results] != expected:
    raise RuntimeError(f"Unexpected IDs or payloads: {results!r}")

for row_id, score, payload in results:
    print(row_id, score, payload.decode("utf-8"))
