import struct

import redis


index = "article_updates"
row_id = 42
text_key = f"article:{row_id}:text"

with redis.Redis(
    host="127.0.0.1", port=6384, protocol=3, decode_responses=False,
) as client:
    client.execute_command(
        "SKEG.VINDEX.CREATE", index, 4,
        "KIND", "tq2", "BACKEND", "disk", "PERSISTENCE", "durable",
    )
    client.set(text_key, b"Use the reset link on the login page.")
    client.execute_command(
        "SKEG.VSET", index, row_id, struct.pack("<4f", 1.0, 0.0, 0.0, 0.0),
        "PAYLOAD", b"topic=account revision=1",
    )

    new_text = b"Use the reset link, or follow the account recovery steps."
    new_vector = struct.pack("<4f", 0.8, 0.6, 0.0, 0.0)
    new_payload = b"topic=account revision=2"
    client.set(text_key, new_text)
    client.execute_command(
        "SKEG.VSET", index, row_id, new_vector, "PAYLOAD", new_payload,
    )

    vector, payload, _version, _incarnation = client.execute_command(
        "SKEG.VGET", index, row_id, "WITHPAYLOAD",
    )
    if vector != new_vector or payload != new_payload:
        raise RuntimeError("The stored vector or payload differs from the update")
    if client.get(text_key) != new_text:
        raise RuntimeError("The stored text differs from the update")
    print(f"Article {row_id}: updated text, vector and payload verified")

    removed_vector = client.execute_command("SKEG.VDEL", index, row_id)
    removed_text = client.delete(text_key)
    if (removed_vector, removed_text) != (1, 1):
        raise RuntimeError("Expected both deletes to remove a record")
    if client.execute_command("SKEG.VGET", index, row_id) is not None:
        raise RuntimeError("The vector is still present")
    if client.get(text_key) is not None:
        raise RuntimeError("The text is still present")
    print(f"Article {row_id}: deleted text and vector verified absent")

    client.execute_command("SKEG.VINDEX.DROP", index)
