#!/bin/sh

if [ -z "$1" ]; then
  echo "Usage: $(basename "$0") <youtube_url>"
  exit 1
fi

url="$1"

processVideo() {
  videoUrl="$1"

  echo "Fetching available formats for video: ${videoUrl}"
  formats=$(yt-dlp -F "${videoUrl}")
  if [ "$#" -ne 0 ]; then
    echo "Error: Failed to fetch formats for ${videoUrl}"
    echo "Is yt-dlp installed and the URL valid?"
    return
  fi

  videoFormat=$(echo "${formats}" | grep 'mp4' | grep -E 'avc1' \
    | awk '{ for (i=1; i<=NF; i++) if ($i ~ /k$/) tbr=$i; print $1, tbr }' \
    | sort -k2 -nr | awk '{ print $1 }' | head -n 1)

  if [ -z "${videoFormat}" ]; then
    echo "No AVC1 video format found, falling back to any MP4 format."
    videoFormat=$(echo "${formats}" | grep 'mp4' \
      | awk '{ for (i=1; i<=NF; i++) if ($i ~ /k$/) tbr=$i; print $1, tbr }' \
      | sort -k2 -nr | awk '{ print $1 }' | head -n 1)
  fi

  audioFormat=$(echo "${formats}" | grep 'm4a' \
    | awk '{ for (i=1; i<=NF; i++) if ($i ~ /k$/) tbr=$i; print $1, tbr }' \
    | sort -k2 -nr | awk '{ print $1 }' | head -n 1)

  if [ -z "${videoFormat}" ] || [ -z "${audioFormat}" ]; then
    echo "Error: No compatible MP4 video or M4A audio formats found for ${videoUrl}!"
    return
  fi

  echo "Selected video format: ${videoFormat} [MP4 : AVC1 preferred]"
  echo "Selected audio format: ${audioFormat} [M4A : highest quality]"

  echo "Downloading video with yt-dlp..."
  yt-dlp --restrict-filenames \
    -f "${videoFormat}+${audioFormat}" \
    --merge-output-format mp4 "${videoUrl}"

  if [ "$#" -ne 0 ]; then
    echo "Error: Failed to download video. Check the format IDs and URL."
  fi
}

isPlaylist() {
  if echo "${url}" | grep -q "list="; then
    return 0
  else
    return 1
  fi
}

if isPlaylist; then
  echo "Processing playlist..."
  videoUrls=$(yt-dlp --flat-playlist --get-url "${url}")

  if [ -z "${videoUrls}" ]; then
    echo "Error: No videos found in the playlist. Is the URL correct?"
    exit 1
  fi

  for videoUrl in ${videoUrls}; do
    echo "Processing video: ${videoUrl}"
    processVideo "${videoUrl}"
  done
else
  echo "Processing single video..."
  processVideo "${url}"
fi
