#!/usr/bin/env bash
# Compare native ZEX vs system zstd (and lz4 if present) on a corpus file.
#
# ZEX does NOT link libzstd/liblz4 — this script only shells out to CLIs for
# an apples-to-apples wall-clock / size table.
#
# Usage:
#   ./scripts/bench_compare.sh              # synthetic ~2 MiB corpus
#   ./scripts/bench_compare.sh /path/file   # your file
#   ITERS=5 ./scripts/bench_compare.sh      # average over N runs (default 3)
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

ITERS="${ITERS:-3}"
CORPUS="${1:-}"
GENERATED=0
if [[ -z "$CORPUS" ]]; then
  CORPUS="$(mktemp /tmp/zex_corpus.XXXXXX.bin)"
  GENERATED=1
  # ~2 MiB semi-repetitive text + binary mix
  python3 - <<'PY' > "$CORPUS"
data = (b"The quick brown fox jumps over the lazy dog. " * 80 + bytes(range(256))) * 80
import sys
sys.stdout.buffer.write(data)
PY
  echo "Generated corpus: $CORPUS ($(wc -c < "$CORPUS") bytes)"
else
  echo "Using corpus: $CORPUS ($(wc -c < "$CORPUS") bytes)"
fi

ZEX="${ROOT}/target/release/zexc"
if [[ ! -x "$ZEX" ]]; then
  echo "Building release zexc..."
  cargo build --release -q
fi

SIZE=$(wc -c < "$CORPUS" | tr -d ' ')
TMP=$(mktemp -d /tmp/zex_bench.XXXXXX)
cleanup() {
  rm -rf "$TMP"
  if [[ "$GENERATED" -eq 1 ]]; then
    rm -f "$CORPUS"
  fi
}
trap cleanup EXIT

# Average wall time over ITERS runs (seconds float).
run_time_avg() {
  local sum=0
  local i
  for ((i = 0; i < ITERS; i++)); do
    local start end
    start=$(date +%s.%N)
    "$@" >/dev/null 2>&1
    end=$(date +%s.%N)
    sum=$(python3 -c "print($sum + ($end - $start))")
  done
  python3 -c "print(f'{$sum / $ITERS:.4f}')"
}

mib_s() {
  local bytes="$1" secs="$2"
  python3 -c "b=float('$bytes'); s=max(float('$secs'), 1e-9); print(f'{b/s/1024/1024:.1f}')"
}

printf "\nNative ZEX vs external CLIs (ITERS=%s) — no library linkage to zstd/lz4\n" "$ITERS"
printf "%-18s %10s %10s %12s %12s\n" "tool" "size" "ratio%" "c_MiB/s" "d_MiB/s"
printf "%s\n" "--------------------------------------------------------------------"

bench_zex() {
  local label="$1" mode="$2" level="$3"
  local out="$TMP/${label// /-}.zex" plain="$TMP/${label// /-}.out"
  local ct dt sz
  # Warmup
  "$ZEX" compress "$CORPUS" "$out" -m "$mode" -l "$level" -q >/dev/null 2>&1 || true
  ct=$(run_time_avg "$ZEX" compress "$CORPUS" "$out" -m "$mode" -l "$level" -q)
  sz=$(wc -c < "$out" | tr -d ' ')
  dt=$(run_time_avg "$ZEX" decompress "$out" "$plain" -q)
  cmp -s "$CORPUS" "$plain"
  local ratio cms dms
  ratio=$(python3 -c "print(f'{100*float($sz)/float($SIZE):.2f}')")
  cms=$(mib_s "$SIZE" "$ct")
  dms=$(mib_s "$SIZE" "$dt")
  printf "%-18s %10s %10s %12s %12s\n" "$label" "$sz" "$ratio" "$cms" "$dms"
}

bench_zex "zex turbo-1" turbo 1
bench_zex "zex turbo-2" turbo 2
bench_zex "zex bal-3" balanced 3
bench_zex "zex bal-6" balanced 6
bench_zex "zex max-12" max 12
bench_zex "zex max-19" max 19

if command -v zstd >/dev/null 2>&1; then
  for lv in 1 3 9 19; do
    local_out="$TMP/zstd${lv}.zst"
    plain="$TMP/zstd${lv}.out"
    zstd -f -"$lv" -o "$local_out" -- "$CORPUS" >/dev/null 2>&1 || true
    ct=$(run_time_avg zstd -f -"$lv" -o "$local_out" -- "$CORPUS")
    sz=$(wc -c < "$local_out" | tr -d ' ')
    dt=$(run_time_avg zstd -d -f -o "$plain" -- "$local_out")
    cmp -s "$CORPUS" "$plain"
    ratio=$(python3 -c "print(f'{100*float($sz)/float($SIZE):.2f}')")
    cms=$(mib_s "$SIZE" "$ct")
    dms=$(mib_s "$SIZE" "$dt")
    printf "%-18s %10s %10s %12s %12s\n" "zstd -$lv" "$sz" "$ratio" "$cms" "$dms"
  done
else
  echo "(zstd not in PATH — skip)"
fi

if command -v lz4 >/dev/null 2>&1; then
  for args in "" "-9"; do
    label="lz4 ${args:-default}"
    local_out="$TMP/lz4${args}.lz4"
    plain="$TMP/lz4.out"
    # shellcheck disable=SC2086
    lz4 -f $args -q "$CORPUS" "$local_out" >/dev/null 2>&1 || true
    # shellcheck disable=SC2086
    ct=$(run_time_avg lz4 -f $args -q "$CORPUS" "$local_out")
    sz=$(wc -c < "$local_out" | tr -d ' ')
    dt=$(run_time_avg lz4 -d -f -q "$local_out" "$plain")
    cmp -s "$CORPUS" "$plain"
    ratio=$(python3 -c "print(f'{100*float($sz)/float($SIZE):.2f}')")
    cms=$(mib_s "$SIZE" "$ct")
    dms=$(mib_s "$SIZE" "$dt")
    printf "%-18s %10s %10s %12s %12s\n" "$label" "$sz" "$ratio" "$cms" "$dms"
  done
else
  echo "(lz4 not in PATH — skip; install lz4 package to compare speed target)"
fi

echo
echo "Corpus bytes: $SIZE"
echo "Note: external tools are comparison only — ZEX codec is 100% native."
echo "Done."
