#!/bin/bash
# YouTube Playlist Import Helper
# This script helps you copy video URLs to clipboard for easy playlist creation

PLAYLISTS_DIR="$(dirname "$0")"
CLIPBOARD_CMD=""

# Detect clipboard command
if command -v xclip &> /dev/null; then
    CLIPBOARD_CMD="xclip -selection clipboard"
elif command -v xsel &> /dev/null; then
    CLIPBOARD_CMD="xsel --clipboard --input"
elif command -v wl-copy &> /dev/null; then
    CLIPBOARD_CMD="wl-copy"
else
    echo "No clipboard utility found. Install xclip, xsel, or wl-clipboard."
    echo "The URLs will be displayed and you can copy them manually."
fi

echo "========================================"
echo "  YouTube Playlist Import Helper"
echo "========================================"
echo ""
echo "Available playlists:"
echo ""

i=1
for f in "$PLAYLISTS_DIR"/*.m3u; do
    if [ -f "$f" ]; then
        name=$(basename "$f" .m3u)
        count=$(grep -c "^https://" "$f" 2>/dev/null || echo 0)
        echo "  $i) $name ($count videos)"
        ((i++))
    fi
done

echo ""
echo "  A) Copy ALL playlists URLs"
echo "  Q) Quit"
echo ""
echo -n "Select a playlist to copy URLs (1-10, A, or Q): "
read choice

copy_urls() {
    local file="$1"
    local urls=$(grep "^https://" "$file")
    if [ -n "$CLIPBOARD_CMD" ]; then
        echo "$urls" | $CLIPBOARD_CMD
        echo ""
        echo "✓ URLs copied to clipboard!"
        echo "  Now go to YouTube and create a new playlist."
        echo "  You can paste all URLs at once using Ctrl+V."
    else
        echo ""
        echo "URLs:"
        echo "$urls"
    fi
}

case $choice in
    [1-9])
        file=$(ls "$PLAYLISTS_DIR"/*.m3u 2>/dev/null | sed -n "${choice}p")
        if [ -f "$file" ]; then
            copy_urls "$file"
        else
            echo "Invalid selection"
        fi
        ;;
    10)
        copy_urls "$PLAYLISTS_DIR/10_Environmental_Storytelling_Game_Design.m3u"
        ;;
    [Aa])
        all_urls=$(grep "^https://" "$PLAYLISTS_DIR"/*.m3u 2>/dev/null)
        if [ -n "$CLIPBOARD_CMD" ]; then
            echo "$all_urls" | $CLIPBOARD_CMD
            echo ""
            echo "✓ All URLs copied to clipboard!"
            echo "  Total: $(echo "$all_urls" | wc -l) videos"
        else
            echo ""
            echo "All URLs:"
            echo "$all_urls"
        fi
        ;;
    [Qq])
        echo "Goodbye!"
        exit 0
        ;;
    *)
        echo "Invalid selection"
        ;;
esac