#!/bin/bash

# Ask where to place the MP3 files
read -p "Place MP3s in same folder as MP4s? (y/n) [y]: " same_folder
same_folder=${same_folder:-y}

if [[ "$same_folder" =~ ^[Nn]$ ]]; then
    read -p "Enter output folder path: " output_folder
    mkdir -p "$output_folder"
else
    output_folder=""
fi

# Get default values from folder structure
# Current directory is "The Energies of Love"
default_album=$(basename "$PWD")
# Parent directory is "Donna Eden & David Feinstein"
default_album_artist=$(basename "$(dirname "$PWD")")

# Prompt for metadata with defaults
read -p "Enter Album Artist [$default_album_artist]: " album_artist
album_artist=${album_artist:-$default_album_artist}

read -p "Enter Release Date (YYYY): " release_date

echo ""
echo "Processing MP4 files..."
echo "Album Artist: $album_artist"
echo ""

counter=0

# Process all mp4 files in subdirectories
for file in */*.mp4 *.mp4; do
    # Skip if file doesn't exist
    [ -e "$file" ] || continue
    
    dir=$(dirname "$file")
    filename=$(basename "$file" .mp4)
    
    # Determine album based on folder structure
    if [ "$dir" != "." ]; then
        # File is in subfolder (Intro, week1, week2, etc.)
        album=$(basename "$dir")
    else
        # File is in current directory
        album="$default_album"
    fi
    
    # Set output location
    if [ -n "$output_folder" ]; then
        # Create matching folder structure in output folder
        if [ "$dir" != "." ]; then
            mkdir -p "$output_folder/$dir"
            output="$output_folder/$dir/${filename}.mp3"
        else
            output="$output_folder/${filename}.mp3"
        fi
    else
        output="$dir/${filename}.mp3"
    fi
    
    # Skip if already exists
    if [ -f "$output" ]; then
        echo "Skip: $filename (exists)"
        continue
    fi
    
    # Get track number
    track_num=$(echo "$filename" | grep -oP '^\d+')
    
    echo "Converting: $filename"
    echo "  Album: $album"
    
    # Convert using temp file
    temp_file="/tmp/convert_$$.mp3"
    
    if [ -n "$track_num" ]; then
        ffmpeg -i "$file" -vn -acodec libmp3lame -q:a 0 \
          -metadata title="$filename" \
          -metadata track="$track_num" \
          -metadata album_artist="$album_artist" \
          -metadata artist="$album_artist" \
          -metadata album="$album" \
          -metadata date="$release_date" \
          "$temp_file" -y >/dev/null 2>&1
    else
        ffmpeg -i "$file" -vn -acodec libmp3lame -q:a 0 \
          -metadata title="$filename" \
          -metadata album_artist="$album_artist" \
          -metadata artist="$album_artist" \
          -metadata album="$album" \
          -metadata date="$release_date" \
          "$temp_file" -y >/dev/null 2>&1
    fi
    
    if [ -f "$temp_file" ]; then
        mv "$temp_file" "$output"
        echo "  ✓ Done"
        ((counter++))
    else
        echo "  ✗ Failed"
    fi
done

echo ""
echo "Converted $counter files"
