#!/usr/bin/env bash
set -euo pipefail

BIN="${1:-target/x86_64-unknown-linux-musl/release/ipc-ring48}"
ITERATIONS="${2:-1000}"

if [[ ! -x "$BIN" ]]; then
  echo "binary not executable: $BIN" >&2
  exit 1
fi

measure_ms() {
  python3 - "$@" <<'PY'
import subprocess
import sys
import time

iterations = int(sys.argv[1])
mode = sys.argv[2]
bin_path = sys.argv[3]

subprocess.run([bin_path, "unlink"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
subprocess.run([bin_path, "init", "2048"], check=True, stdout=subprocess.DEVNULL)

start = time.perf_counter_ns()

if mode == "u64":
    for _ in range(iterations):
        subprocess.run([bin_path, "push-u64", "1", "7", "13", "43", "127", "255"], check=True, stdout=subprocess.DEVNULL)
        subprocess.run([bin_path, "pop-u64"], check=True, stdout=subprocess.DEVNULL)
elif mode == "bin":
    payload = bytes(range(48))
    in_path = "/tmp/ipc-ring48-bench-in.bin"
    out_path = "/tmp/ipc-ring48-bench-out.bin"
    with open(in_path, "wb") as f:
        f.write(payload)
    for _ in range(iterations):
        subprocess.run([bin_path, "push-file", in_path], check=True, stdout=subprocess.DEVNULL)
        with open(out_path, "wb") as out:
            subprocess.run([bin_path, "pop-bin"], check=True, stdout=out)
else:
    raise SystemExit(f"unknown mode: {mode}")

elapsed = time.perf_counter_ns() - start
subprocess.run([bin_path, "unlink"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print(f"{elapsed / iterations / 1_000_000:.6f}")
PY
}

printf 'ipc-ring48 CLI benchmark\n'
printf 'binary: %s\n' "$BIN"
printf 'iterations: %s\n' "$ITERATIONS"
printf 'push-u64 + pop-u64 mean ms: '
measure_ms "$ITERATIONS" u64 "$BIN"
printf 'push-file + pop-bin mean ms: '
measure_ms "$ITERATIONS" bin "$BIN"
