#!/usr/bin/env bash
#
# Wall-clock + compressed-size comparison between FLAC and LAC on the
# local corpus directory. Diagnostic only — not part of CI.
#
# Usage:
#   benches/compare-flac.sh [corpus_dir]
#
# Output columns (tab-separated, stable for piping into column -t):
#
#   file   flac_ms   flac_bytes   [matching LAC line from `cargo test`]
#
# For the LAC side, run `cargo test --test corpus --release -- --nocapture`
# and correlate `lac_enc_ms` / `lac=<bytes>` values against the filenames
# printed here. Two separate invocations because automating the join is
# more fragile than eyeballing it for the six files the corpus contains.

set -euo pipefail

CORPUS_DIR="${1:-corpus}"

if ! command -v flac > /dev/null 2>&1; then
    echo "flac CLI not found in PATH; install the flac package" >&2
    exit 1
fi
if [[ ! -d "$CORPUS_DIR" ]]; then
    echo "corpus directory not found: $CORPUS_DIR" >&2
    exit 1
fi

# Header. Columns cover both FLAC modes — default (`-5`, what most
# production pipelines actually use) and `--best` (`-8`, the ceiling
# `tests/corpus.rs` asserts its ratios against). `column -t` on the
# output aligns to the printf format below.
printf "%-50s\t%12s\t%14s\t%12s\t%14s\n" \
    "file" "flac_d_ms" "flac_d_bytes" "flac_b_ms" "flac_b_bytes"

# Shell globs are unordered across filesystems; sort for stable output.
shopt -s nullglob
files=("$CORPUS_DIR"/*.wav)
IFS=$'\n' files=($(sort <<< "${files[*]}"))
unset IFS

# Warm-up invocation against the first file: the very first `flac` exec
# in a shell session pays dynamic-linker + page-fault costs that aren't
# representative of steady-state. Subsequent runs don't repay them.
if [[ ${#files[@]} -gt 0 ]]; then
    flac --stdout --best --silent "${files[0]}" > /dev/null 2>&1 || true
fi

for f in "${files[@]}"; do
    # `date +%s%N` gives nanoseconds since epoch on GNU coreutils. Not
    # portable to BSD `date`, but this script is Linux-only by design
    # (matches the CI runner environment).
    #
    # Two invocations per file: default (`-5`) first, then `--best`.
    # Ordering is deliberate: the default pass also warms the OS file
    # cache, so `--best` sees warm-cache I/O and its time reflects the
    # compute cost, not disk read.
    start_ns=$(date +%s%N)
    flac_d_bytes=$(flac --stdout --silent "$f" 2> /dev/null | wc -c)
    mid_ns=$(date +%s%N)
    flac_b_bytes=$(flac --stdout --best --silent "$f" 2> /dev/null | wc -c)
    end_ns=$(date +%s%N)
    flac_d_ms=$(( (mid_ns - start_ns) / 1000000 ))
    flac_b_ms=$(( (end_ns - mid_ns) / 1000000 ))
    printf "%-50s\t%12d\t%14d\t%12d\t%14d\n" \
        "$(basename "$f")" "$flac_d_ms" "$flac_d_bytes" "$flac_b_ms" "$flac_b_bytes"
done
