#!/usr/bin/env python3
import os
import socket
import time


SCRIPT_PATH = os.getenv("HOTPATH_LUA", "/etc/opensips/lisglosips_hotpath.lua")
REDIS_HOST = os.getenv("REDIS_PROXY_HOST", "127.0.0.1")
REDIS_PORT = int(os.getenv("REDIS_PROXY_PORT", "6380"))


def enc(parts: list[str]) -> bytes:
    output = f"*{len(parts)}\r\n".encode("utf-8")
    for part in parts:
        data = part.encode("utf-8")
        output += f"${len(data)}\r\n".encode("utf-8") + data + b"\r\n"
    return output


with open(SCRIPT_PATH, "r", encoding="utf-8") as handle:
    script = handle.read()

last_error: Exception | None = None
for _ in range(20):
    try:
        with socket.create_connection((REDIS_HOST, REDIS_PORT), timeout=2) as sock:
            sock.sendall(enc(["SCRIPT", "LOAD", script]))
            response = sock.recv(4096)
            if not response.startswith(b"$"):
                raise SystemExit(f"unexpected Redis response while loading Lua: {response[:80]!r}")
            raise SystemExit(0)
    except OSError as exc:
        last_error = exc
        time.sleep(0.25)

raise SystemExit(f"could not connect to Redis proxy: {last_error}")
