#!/usr/bin/env bash
set -euo pipefail
# POS: media mp3 — Download audio as MP3 (yt-dlp)
# POS_FLAGS: --output --no-playlist --cookies --by-artist --dry-run

source "$(dirname "$0")/../lib/common.sh" 2>/dev/null || source "$(dirname "$0")/common.sh"

# --dry-run is parsed before the deps guards (below): it previews the yt-dlp
# command without requiring yt-dlp/ffmpeg to be installed.
DRY_RUN=0
for arg in "$@"; do
    [ "$arg" = "--dry-run" ] && DRY_RUN=1
done

# Deps guards sit before -h|--help (help also errors on a box missing the deps).
if [ "$DRY_RUN" -eq 0 ]; then
    command -v yt-dlp &>/dev/null || err "yt-dlp not found — install with: sudo apt install yt-dlp"
    command -v ffmpeg &>/dev/null || err "ffmpeg not found — install with: sudo apt install ffmpeg"
fi

OUT_DIR="$HOME/Music"
BY_ARTIST=0
EXTRA_ARGS=()

usage() {
    cat <<EOF
Usage: pos media mp3 [options] <url>

Download audio from a URL and convert to MP3 via yt-dlp.

Options:
  -o, --output <dir>    Output directory (default: $OUT_DIR)
  --by-artist           Organize as <dir>/<artist>/<title>.mp3
  --no-playlist         Download only the single video
  --cookies <file>      Netscape cookies.txt for age-gated content
  --dry-run             Print the yt-dlp command without running it
  -h, --help            This help

Examples:
  pos media mp3 https://youtube.com/watch?v=dQw4w9WgXcQ
  pos media mp3 --by-artist --no-playlist https://youtu.be/dQw4w9WgXcQ
  pos media mp3 --cookies ~/cookies.txt https://vimeo.com/123
EOF
    exit 0
}

URL=""
while [[ $# -gt 0 ]]; do
    case "$1" in
        -h|--help) usage ;;
        -o|--output)
            [ $# -ge 2 ] || err "--output needs a value"
            OUT_DIR="$2"; shift 2 ;;
        --by-artist) BY_ARTIST=1; shift ;;
        --no-playlist) EXTRA_ARGS+=(--no-playlist); shift ;;
        --cookies)
            [ $# -ge 2 ] || err "--cookies needs a value"
            [ -f "$2" ] || err "cookies file not found: $2"
            EXTRA_ARGS+=(--cookies "$2"); shift 2 ;;
        --dry-run) DRY_RUN=1; shift ;;
        -*) err "Unknown option: $1 (see --help)" ;;
        *)
            [ -z "$URL" ] && URL="$1" && shift || err "Unexpected argument: $1" ;;
    esac
done
[ -n "$URL" ] || usage

if [ "$BY_ARTIST" -eq 1 ]; then
    OUT_TEMPLATE="$OUT_DIR/%(artist,uploader)s/%(title)s.%(ext)s"
else
    OUT_TEMPLATE="$OUT_DIR/%(title)s.%(ext)s"
fi

args=(yt-dlp -x --audio-format mp3 --audio-quality 0
    --embed-metadata --embed-chapters
    --embed-thumbnail --convert-thumbnails jpg
    --parse-metadata "%(artist,uploader)s:%(artist)s"
    --no-overwrites
    -o "$OUT_TEMPLATE"
    "${EXTRA_ARGS[@]}" "$URL")

if [ "$DRY_RUN" -eq 1 ]; then
    echo "yt-dlp ${args[*]:1}"
else
    spawn "downloading audio → $OUT_DIR" "${args[@]}"
fi
