#!/bin/sh

tmpdir="$(mktemp -d)"
monitor="$(pactl get-default-sink).monitor"

echo "Listening on $monitor (Shazam)..."
result="$(songrec recognize -d "$monitor" -j)"

artist="$(printf '%s' "$result" | jq -r '.track.subtitle // empty')"
title="$(printf '%s' "$result" | jq -r '.track.title // empty')"

if [ -z "$artist" ] || [ -z "$title" ]; then
    echo "Could not identify song. Even chaos has limits."
    rm -rf "$tmpdir"
    exit 1
fi

query="$artist - $title"

echo
echo "Identified: $query"
echo
echo "Searching YouTube for:"
echo "  $query"
echo

yt-dlp "ytsearch1:$query" \
  --print "━━━━━━━━━━━━━━━━━━━━━━━" \
  --print "Title:     %(title)s" \
  --print "Channel:   %(uploader)s" \
  --print "Duration:  %(duration_string)s" \
  --print "URL:       %(webpage_url)s" \
  --print "━━━━━━━━━━━━━━━━━━━━━━━"

echo
read -p "Download this? [y/N] " confirm

if [[ "$confirm" =~ ^[Yy]$ ]]; then
    yt-dlp -x --audio-format m4a -f bestaudio \
        "ytsearch1:$query" \
	-o "$tmpdir/download.%(ext)s"

    file="$(ls "$tmpdir"/download.* 2>/dev/null | head -n1)"

    if [[ -n "$file" ]]; then
        script_dir="$(cd "$(dirname "$0")" && pwd)"
        "$script_dir/retag" "$tmpdir" --commit --no-backup

        tag_artist="$(ffprobe -v error -show_entries format_tags=artist -of default=nw=1:nk=1 "$file")"
        tag_album="$(ffprobe -v error -show_entries format_tags=album  -of default=nw=1:nk=1 "$file")"
        tag_title="$(ffprobe -v error -show_entries format_tags=title  -of default=nw=1:nk=1 "$file")"

        a="${tag_artist:-$artist}"
        b="${tag_album:-Unknown Album}"
        t="${tag_title:-$title}"

        # filesystem-safe: replace path separator
        a="${a//\//_}"
        b="${b//\//_}"
        t="${t//\//_}"

        dest="$HOME/Music/$a/$b"
        mkdir -p "$dest"
        mv "$file" "$dest/$t.m4a"
        echo "Saved to: $dest/$t.m4a"
    else
        echo "Download failed. Even chaos has limits."
    fi

    rm -rf "$tmpdir"
else
    rm -rf "$tmpdir"
    echo "Aborted."
fi

read -n 1 -s -r -p "Done. Press any key to close."
