#!/bin/bash
# Sox Transpose, change the pitch of selected WAV files, including a 'Solfeggio' option.
# Concept and Testing by Glen MacArthur, coded by Google Gemini 3.

LOG="$HOME/.avl-mxe-file-action.log"
echo "--- Sox YAD Pitch Shift Started: $(date) ---" > "$LOG"

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

# 1. YAD Dialog
# Changed default value to 0 so "Solfeggio Only" is easier to trigger
DATA=$(yad --title="Sox Transpose" \
    --image="/usr/local/share/icons/custom/sox-app.png" \
    --window-icon="/usr/local/share/icons/custom/sox.png" \
    --form \
    --text="<b>Note:</b> Leave Shift at 0 to apply 528Hz offset only." \
    --field="Semitone Shift:NUM" "0!-12..12!1!0" \
    --field="Apply 528Hz (Solfeggio) Offset:CHK" "FALSE" \
    --button="OK:0" --button="Cancel:1" --width=400)

[ $? -ne 0 ] && exit 1

# Extract values
VAL=$(echo "$DATA" | cut -d'|' -f1 | cut -d'.' -f1)
SOLFEGGIO=$(echo "$DATA" | cut -d'|' -f2)

# 2. Calculate Total Cents & Filename Suffix
CENTS=$(echo "$VAL * 100" | bc)

if [ "$SOLFEGGIO" == "TRUE" ]; then
    CENTS=$(echo "$CENTS + 15.67" | bc)
    if [ "$VAL" -eq 0 ]; then
        SUFFIX="528Hz_Only"
    else
        SUFFIX="shift_${VAL}_528Hz"
    fi
else
    # If not using Solfeggio, just use the semitone value
    SUFFIX="shift_${VAL}"
fi

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

    process_file() {
        local input="$1"
        local output="${input%.*}-${SUFFIX}.wav"
        
        # Don't process if no change is requested (0 cents)
        if (( $(echo "$CENTS == 0" | bc -l) )); then
             cp "$input" "${input%.*}-copy.wav"
             echo "No shift requested for $input, created copy." >> "$LOG"
        else
             sox -V3 "$input" "$output" pitch "$CENTS" >> "$LOG" 2>&1
        fi
    }

    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 Transpose" "Completed: ${SUFFIX} applied! ✅"