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

# ── tweak these to suit your needs ─────────────────────────
BITRATE="64k"
SAMPLERATE="16000"
CHANNELS="1"
# ──────────────────────────────────────────────────────────

# Find all files with spaces and fix
find . -maxdepth 1 -type f -name "* *" -exec bash -c 'for f; do mv -- "$f" "${f// /_}"; done' _ {} +

# find every real .wav under here, but skip macOS metadata files (._foo.wav)
find . -type f -iname '*.wav' ! -iname '._*' -print0 |
while IFS= read -r -d '' wav; do
  m4a="${wav%.*}.m4a"

  # 1) sanity check: does .wav actually exist?
  if [[ ! -f "$wav" ]]; then
    echo "⚠️  Skipping missing file: $wav"
    continue
  fi

  # 2) skip if the target .m4a is already there
  if [[ -f "$m4a" ]]; then
    echo "⏭️  Already exists, skipping: $m4a"
    continue
  fi

  # 3) do the conversion
  echo "🔊 Converting: '$wav' → '$m4a'"
  ffmpeg -hide_banner -loglevel info -y \
    -i "$wav" \
    -c:a aac \
    -b:a "$BITRATE" \
    -ar "$SAMPLERATE" \
    -ac "$CHANNELS" \
    -map_metadata 0 \
    "$m4a" \
  && echo "✅  Done: $m4a" \
  || echo "❌  Failed: $wav"

done
