#!/bin/bash

# Base directory for all operations
BASE_DIR="$HOME/Dropbox/__INBOX_RECIEVING/__AUDIO-IN"
INPUT_DIR="$BASE_DIR/_02_Converted_MP3"
OUTPUT_DIR="$BASE_DIR/_03_Audacity_Processing"
TRANSCRIPT_DIR="$BASE_DIR/_05_AUTO_Transcribed"
LOGS_DIR="$BASE_DIR/_LOGS"

# Move log file outside of processing directory
LOG_FILE="$LOGS_DIR/transcription_log.txt"

echo "Watching for incoming MP3s."

# Watch for new files, excluding both .DS_Store and .txt files
fswatch -0 -e "\.DS_Store$" -e "\.txt$" "$INPUT_DIR" | while IFS= read -r -d $'\0' file; do

  filename=$(basename "$file")
  filename_no_ext="${filename%.*}"
  transcript_file="$TRANSCRIPT_DIR/${filename_no_ext}.txt"
  output_mp3="$OUTPUT_DIR/${filename_no_ext}.mp3" # Added output MP3 path

# Check if the file still exists
    if [ ! -f "$file" ]; then
        echo "Ignoring deleted or moved file: $file" | tee -a "$LOG_FILE"
        continue
    fi

# Check if file already processed (in output directory)
  if [ -f "$output_mp3" ]; then
    echo "Skipping already processed file: $file" | tee -a "$LOG_FILE"
    continue # Skip to the next file
  fi

# More robust check to ensure we only process MP3 files
if file "$file" | grep -q "MP3"; then
  echo "Detected a new MP3 file to process." | tee -a "$LOG_FILE"
  mv "$file" "$OUTPUT_DIR/"
  echo "Moved MP3 to next step for Audacity processing." | tee -a "$LOG_FILE"

  else
    echo "Ignoring non-MP3 file: $file" | tee -a "$LOG_FILE"
  fi
    echo "Transcription Process Complete."

done