import struct

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


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


with redis.Redis(
    host="127.0.0.1", port=6382, protocol=2, decode_responses=False,
    socket_connect_timeout=5, socket_timeout=30, retry=Retry(NoBackoff(), 0),
) as client:
    index = "batch_ingestion_demo"
    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"topic=account revision=1"),
        (2, [0.0, 1.0], b"topic=billing revision=1"),
        (3, [0.8, 0.6, 0.0, 0.0], b"topic=account revision=1"),
    ]
    command = ["SKEG.VMSET", index]
    for row_id, coordinates, payload in rows:
        command.extend((row_id, vector(coordinates), payload))

    outcomes = client.execute_command(*command)
    if not isinstance(outcomes, list) or len(outcomes) != len(rows):
        raise RuntimeError("Incomplete or unexpected batch response")

    failed = []
    for (row_id, _, _), outcome in zip(rows, outcomes):
        if outcome == b"OK":
            print(row_id, "stored")
        elif isinstance(outcome, redis.exceptions.ResponseError):
            failed.append(row_id)
            print(row_id, "error:", outcome)
        else:
            raise RuntimeError(f"Unexpected outcome for row {row_id}: {outcome!r}")

    if failed != [2]:
        raise RuntimeError("Unexpected failures; inspect them before repairing")

    if client.execute_command("SKEG.VGET", index, 2) is not None:
        raise RuntimeError("The rejected row should be absent")

    corrected = vector([0.0, 1.0, 0.0, 0.0])
    client.execute_command(
        "SKEG.VSET", index, 2, corrected, "PAYLOAD", b"topic=billing revision=1",
    )
    expected = {1: vector(rows[0][1]), 2: corrected, 3: vector(rows[2][1])}
    for row_id, expected_vector in expected.items():
        raw = client.execute_command("SKEG.VGET", index, row_id)
        if raw != expected_vector:
            raise RuntimeError(f"Unexpected vector for row {row_id}")
        print(row_id, struct.unpack("<4f", raw))
