#!/bin/bash

# Configuration
INPUT_DIR="$HOME/Dropbox/__INBOX_RECIEVING/__AUDIO-IN-RAW/_01_Process_Folder"
OUTPUT_DIR="$HOME/Dropbox/__INBOX_RECIEVING/__AUDIO-IN-RAW/_02_Converted_MP3"
TRANSCRIPT_DIR="$HOME/Dropbox/__INBOX_RECIEVING/__AUDIO-IN-RAW/_04_Transcribed"
FINAL_OUTPUT_DIR="$HOME/Dropbox/__INBOX_RECIEVING/__AUDIO-IN-RAW/_03_Final_Files"
LOG_FILE="$HOME/Dropbox/__INBOX_RECIEVING/__AUDIO-IN-RAW/_03_Final_Files/conversion_log.txt"

echo "Script starting..."
echo "Watching directory: $INPUT_DIR"

# Create directories if they don't exist
mkdir -p "$OUTPUT_DIR" "$TRANSCRIPT_DIR" "$FINAL_OUTPUT_DIR"
echo "Directories created/verified"

process_in_audacity() {
    input_mp3="$1"
    echo "Processing in Audacity: $input_mp3" >> "$LOG_FILE"
    filename=$(basename "$input_mp3")
    filename_no_ext="${filename%.*}"
    output_file="$FINAL_OUTPUT_DIR/${filename_no_ext}_final.mp3"
    
python3 - <<EOF
import time

PIPE_TO_AUDACITY = "/tmp/audacity_script_pipe.to.503"
PIPE_FROM_AUDACITY = "/tmp/audacity_script_pipe.from.503"

def send_command(command):
    """Send a command to Audacity via the named pipe."""
    with open(PIPE_TO_AUDACITY, 'w') as pipe:
        pipe.write(command + '\\n')

    time.sleep(0.1)
    with open(PIPE_FROM_AUDACITY, 'r') as pipe:
        response = pipe.read()
    return response

def process_audio(input_mp3, output_file):
    """Processes the audio in Audacity using mod-script-pipe."""
    send_command(f'Import2: Filename="{input_mp3}"')
    send_command("SelectAll:")
    send_command("HighPassFilter: Frequency=80 Rolloff=48")
    send_command("GraphicEQ: 100=1.5 200=-2.5 300=-2.0 2000=2.5 3000=2.0 8000=1.5 10000=1.0")
    send_command("Compressor: Threshold=-18 Ratio=2.0 AttackTime=0.01 ReleaseTime=0.06 UsePeak=1")
    send_command("Normalize: PeakLevel=-1 RemoveDcOffset=1 ApplyGain=1")
    send_command("Limiter: Type=HardLimit ThresholdLevel=-1 HoldTime=0.01 ApplyMakeupGain=0")
    send_command(f'Export2: Filename="{output_file}" Format="MP3"')
    send_command("RemoveTracks:")
    
    print("Processing complete!")

input_mp3 = "$input_mp3"
output_file = "$FINAL_OUTPUT_DIR/${filename_no_ext}_final.mp3"
process_audio(input_mp3, output_file)
EOF
}

convert_file() {
    input_file="$1"
    echo "Converting file: $input_file" >> "$LOG_FILE"
    filename=$(basename "$input_file")
    filename_no_ext="${filename%.*}"
    output_file="$OUTPUT_DIR/${filename_no_ext}.mp3"
    transcript_file="$TRANSCRIPT_DIR/${filename_no_ext}.txt"

    echo "$(date): Processing $filename" | tee -a "$LOG_FILE"

    if [[ "$input_file" =~ \.(mp4|m4a)$ ]]; then
        echo "Converting to MP3..." | tee -a "$LOG_FILE"
        ffmpeg -i "$input_file" -vn -acodec libmp3lame -q:a 2 "$output_file" 2>> "$LOG_FILE"
        audio_file="$output_file"
    else
        echo "Copying MP3 file..." | tee -a "$LOG_FILE"
        cp "$input_file" "$output_file"
        audio_file="$input_file"
    fi

    if [ -f "$output_file" ]; then
        echo "Output file created successfully" | tee -a "$LOG_FILE"
        if whisper "$OUTPUT_DIR/${filename_no_ext}.mp3" --model base --language en --output_dir "$TRANSCRIPT_DIR" --output_format txt 2>> "$LOG_FILE"; then
            mv "$TRANSCRIPT_DIR/${filename_no_ext}.txt" "$transcript_file"
            process_in_audacity "$output_file"
            rm "$input_file"
            echo "$(date): Successfully processed $filename" | tee -a "$LOG_FILE"
        fi
    else
        echo "Failed to create output file" | tee -a "$LOG_FILE"
    fi
}

watch_directory() {
    echo "Starting directory watch..." | tee -a "$LOG_FILE"
    
    fswatch -0 "$INPUT_DIR" | while read -d "" event
    do
        echo "Event detected: $event" | tee -a "$LOG_FILE"
        if [[ "$event" =~ \.(mp4|mp3|m4a)$ ]]; then
            echo "Valid audio file detected: $event" | tee -a "$LOG_FILE"
            sleep 1
            convert_file "$event"
        else
            echo "Not a valid audio file: $event" | tee -a "$LOG_FILE"
        fi
    done
}

# Start the watcher
watch_directory
