#!/bin/bash

# Set flag file and help file locations
APP_SUPPORT_DIR="$HOME/Library/Application Support/GoStitch"
FLAG_FILE="$APP_SUPPORT_DIR/.first_run_done"
HELP_FILE="$PWD/Credits.html"

show_help() {
    open "$HELP_FILE"
}

mkdir -p "$APP_SUPPORT_DIR"

# If --help argument
if [[ "$1" == "--help" ]]; then
    show_help
    exit 0
fi

# If first run
if [[ ! -f "$FLAG_FILE" ]]; then
    show_help
    touch "$FLAG_FILE"
fi

# Get the directory where this script runs inside the app bundle
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# Path to bundled ffmpeg inside Resources folder
FFMPEG="$SCRIPT_DIR/../Resources/ffmpeg"

# If no arguments (no dropped folders/files), prompt user to pick one folder
if [ "$#" -eq 0 ]; then
  folder=$(osascript -e 'POSIX path of (choose folder with prompt "Select a folder with GoPro clips:")') || exit 1
  set -- "$folder"
fi

for item in "$@"; do
  if [[ -d "$item" ]]; then
    cd "$item" || continue
  elif [[ -f "$item" ]]; then
    cd "$(dirname "$item")" || continue
  else
    echo "Skipping invalid item: $item"
    continue
  fi

  echo "Processing item: $item in directory: $(pwd)"

  # Find GoPro files recursively
  files=()
  while IFS= read -r -d $'\0' file; do
    files+=("$file")
  done < <(find . -type f \( -iname 'GOPR*.MP4' -o -iname 'GX*.MP4' -o -iname 'GH*.MP4' -o -iname 'GP*.MP4' \) -print0 | sort -z)

  if [ ${#files[@]} -eq 0 ]; then
    osascript -e 'display dialog "⚠️ No GoPro .MP4 files found in the selected folder or its subfolders." buttons {"OK"}'
    continue
  fi

  # Create filelist.txt
  > filelist.txt
  for f in "${files[@]}"; do
    abs_path="$(realpath "$f" 2>/dev/null || readlink -f "$f" 2>/dev/null || echo "$PWD/${f#./}")"
    echo "file '$abs_path'" >> filelist.txt
  done

  output_name="$(basename "$PWD")_stitched.mp4"

  # Check ffmpeg executable
  if [ ! -x "$FFMPEG" ]; then
    osascript -e 'display dialog "❌ Bundled ffmpeg not found or not executable." buttons {"OK"}'
    continue
  fi

  # Run ffmpeg concat
  "$FFMPEG" -f concat -safe 0 -i filelist.txt -c copy "$output_name"

  # Clean up
  rm -f filelist.txt

  # Show result dialog and open output folder
  if [ -f "$output_name" ]; then
    osascript -e "display dialog \"✅ Success: '$output_name' created in the folder.\" buttons {\"OK\"}"
    open "$(dirname "$output_name")"
  else
    osascript -e 'display dialog "❌ Error: ffmpeg failed or no output created." buttons {"OK"}'
  fi
done
