#!/bin/bash
# Sox Resample, change the sample rate of selected Audio files.
# Concept and Testing by Glen MacArthur, coded by Google Gemini 3.

LOG="$HOME/.avl-mxe-file-action.log"
: > "$LOG" 

if [ $# -eq 0 ]; then
    echo "No files received." >> "$LOG"
    exit 1
fi

# 1. YAD Dialog with Dropdown
DATA=$(yad --title="Sox Resampler" \
    --image="/usr/local/share/icons/custom/sox-app.png" \
    --window-icon="/usr/local/share/icons/custom/sox.png" \
    --form \
    --field="Target Sample Rate:CBE" "44100!44100!48000!88200!96000!192000" \
    --button="OK:0" --button="Cancel:1" --width=350)

[ $? -ne 0 ] && exit 1

TARGET_RATE=$(echo "$DATA" | cut -d'|' -f1)
LABEL=$(echo "$TARGET_RATE" | awk '{printf "%.1fk", $1/1000}' | sed 's/\.0k/k/')

echo "--- Sox HQ Resampling to ${TARGET_RATE} Started: $(date) ---" > "$LOG"

# 2. Processing Loop
for item in "$@"; do
    [[ "$item" == "bash" ]] && continue

    process_file() {
        local input="$1"
        local output="${input%.*}-${LABEL}.wav"
        
        # 'rate -v' triggers the Very High Quality resampler
        # We use -V3 for verbose logging to catch any clipping or errors
        sox -V3 "$input" "$output" rate -v "$TARGET_RATE" >> "$LOG" 2>&1
    }

    if [ -d "$item" ]; then
        for f in "$item"/*.wav; do
            [ -f "$f" ] && process_file "$f"
        done
    elif [ -f "$item" ]; then
        process_file "$item"
    fi
done

notify-send "Sox Resampler" "HQ Conversion to ${LABEL} Complete! ✅"