"""The skeg quickstart through the Python client.

    python quickstart.py write    create the index, add, search, update, delete
    python quickstart.py check    after a restart: everything is still there

Connection settings come from the environment: SKEG_CLIENT__ADDR (host:port,
default 127.0.0.1:6379), SKEG_CLIENT__USER and SKEG_CLIENT__PASSWORD_FILE.
"""
import os
import struct
import sys
from pathlib import Path

import skeg
from skeg.collection import Collection, Written
from skeg.config import IndexConfig
from skeg.errors import ServerError
from skeg.filter import eq, ge

STATE = Path("quickstart.incarnation")
CONFIG = IndexConfig(dim=8, embedding_space="quickstart", kind="tq2", backend="disk")


def vec(i):
    """Vector i: 1.0 at position i mod 8, and 0.01, 0.02, ... elsewhere."""
    return [1.0 if j == i % 8 else 0.01 * (j + 1) for j in range(8)]


def ids(matches):
    return sorted(m.id for m in matches)


def expect(what, got, want):
    if got != want:
        sys.exit(f"{step} failed: {what}: got {got!r}, expected {want!r}")


def write(c):
    # Opens the index, creating it when it does not exist yet.
    docs = Collection.open(c, "docs", CONFIG)
    expect("persistence", docs.descriptor.persistence, "durable")
    print("created index docs: dim 8, tq2, disk, durable")

    for i in range(1, 7):
        meta = {"lang": "en" if i % 2 else "it", "year": 2018 + i}
        expect(f"add {i}", docs.add(i, vec(i), metadata=meta), Written(id=i))
    print("added vectors 1-6")

    found = docs.search(vec(2), k=10, filter=eq("lang", "it"), with_payload=True)
    expect("lang = it", ids(found), [2, 4, 6])
    print("lang = it -> [2, 4, 6]")
    expect("year >= 2023", ids(docs.search(vec(5), k=10, filter=ge("year", 2023))), [5, 6])
    print("year >= 2023 -> [5, 6]")

    # Writing an existing id replaces its vector and its metadata.
    expect("update 3", docs.add(3, vec(7), metadata={"lang": "it", "year": 2030}), Written(id=3))
    expect("delete 4", docs.delete(4), Written(existed=True, id=4))
    print("updated vector 3, deleted vector 4")
    expect("lang = it", ids(docs.search(vec(2), k=10, filter=eq("lang", "it"))), [2, 3, 6])
    print("lang = it -> [2, 3, 6]")

    STATE.write_text(docs.descriptor.incarnation)
    print(f"incarnation saved to {STATE}")


def check(c):
    # Ask for the index before opening it, so nothing can create it here.
    try:
        info = c.vindex_info("docs")
    except ServerError as e:
        sys.exit(f"check failed: index docs not found ({e})")
    saved = STATE.read_text() if STATE.exists() else None
    expect("incarnation", info.incarnation, saved)
    docs = Collection.open(c, "docs", CONFIG)
    expect("incarnation", docs.descriptor.incarnation, saved)
    print("index docs adopted: same incarnation as before the restart")

    # get() returns the stored vector as little-endian f32 bytes.
    expect("vector 1", docs.get(1), struct.pack("<8f", *vec(1)))
    expect("vector 3", docs.get(3), struct.pack("<8f", *vec(7)))
    expect("vector 4", docs.get(4), None)
    print("vector 3 holds its update, vector 4 is gone")

    found = docs.search(vec(3), k=10, filter=eq("lang", "it"), with_payload=True)
    expect("lang = it", ids(found), [2, 3, 6])
    meta = {m.id: m.metadata for m in found}
    expect("metadata of 3", meta[3], {"lang": "it", "year": 2030})
    expect("metadata of 2", meta[2], {"lang": "it", "year": 2020})
    print("lang = it -> [2, 3, 6]")
    print("vector 3 has lang=it year=2030")
    expect("lang = en", ids(docs.search(vec(1), k=10, filter=eq("lang", "en"))), [1, 5])
    print("lang = en -> [1, 5]")
    expect("4 deleted", 4 in ids(docs.search(vec(4), k=10)), False)


step = sys.argv[1] if len(sys.argv) == 2 else None
if step not in ("write", "check"):
    sys.exit("usage: python quickstart.py write|check")

host, _, port = os.environ.get("SKEG_CLIENT__ADDR", "127.0.0.1:6379").rpartition(":")
user = os.environ.get("SKEG_CLIENT__USER")
with skeg.connect(host, int(port), user=user, password_file=os.environ.get("SKEG_CLIENT__PASSWORD_FILE")) as c:
    print(f"connected to {host}:{port} as {user}")
    if step == "write":
        write(c)
    else:
        check(c)
print(f"{step} ok")
