#!/usr/bin/env bash
# Description: Build benchmark in release mode

# Unified help handler
SCRIPT_NAME="$(basename "$0")"
DESC="$(grep -m1 '^# Description:' "$0" | sed 's/^# Description:[[:space:]]*//')"
print_help() { echo "Usage: $SCRIPT_NAME"; [ -n "$DESC" ] && echo "$DESC"; exit 0; }
case "${1:-}" in -h|--help|help) print_help ;; esac

find_repo_root() {
  local d
  d="$(cd "$(dirname "${BASH_SOURCE[0]}")"/.. && pwd)"
  while [ "$d" != "/" ]; do
    if [ -f "$d/Cargo.toml" ]; then echo "$d"; return; fi
    d="$(dirname "$d")"
  done
  echo "."
}
ROOT="$(find_repo_root)"; cd "$ROOT" || exit 1

TIMESTAMP=$(date +"%Y%m%d_%H%M")
RELEASE_DIR="$ROOT/releases/$TIMESTAMP"
mkdir -p "$RELEASE_DIR"

echo "[build] cargo build --release"
cargo build --release

# Determine host OS/arch for naming
OS=$(uname -s 2>/dev/null || echo unknown)
ARCH=$(uname -m 2>/dev/null || echo unknown)

SRC_BIN=""
DST_NAME="quicfuscate"
case "$OS" in
  Darwin)
    SRC_BIN="$ROOT/target/release/quicfuscate"
    if [ "$ARCH" = "arm64" ]; then
      DST_NAME="QuicFuscate_macos_arm64"
    else
      DST_NAME="QuicFuscate_macos_amd64"
    fi
    ;;
  MINGW*|MSYS*|CYGWIN*|Windows_NT)
    SRC_BIN="$ROOT/target/release/quicfuscate.exe"
    DST_NAME="QuicFuscate_windows_amd64.exe"
    ;;
  Linux)
    SRC_BIN="$ROOT/target/release/quicfuscate"
    if [ "$ARCH" = "aarch64" ]; then
      DST_NAME="QuicFuscate_linux_arm64"
    else
      DST_NAME="QuicFuscate_linux_amd64"
    fi
    ;;
  *)
    SRC_BIN="$ROOT/target/release/quicfuscate"
    DST_NAME="QuicFuscate_${OS}_${ARCH}"
    ;;
esac

if [ -f "$SRC_BIN" ]; then
  echo "[artifact] moving $SRC_BIN -> $RELEASE_DIR/$DST_NAME"
  mv "$SRC_BIN" "$RELEASE_DIR/$DST_NAME"
  chmod +x "$RELEASE_DIR/$DST_NAME" 2>/dev/null || true
  ls -la "$RELEASE_DIR" || true
else
  echo "⚠ Built binary not found at: $SRC_BIN"
fi

echo "[cleanup] cargo clean"
cargo clean
