#!/bin/sh

# Function to perform the YouTube search and play a video
search_and_play() {
    # Prompt the user for a search query
    echo "Search Without Google's Bullshit!:"
    read -r SEARCH_TERM

    # Exit if no input is given
    [ -z "$SEARCH_TERM" ] && return 0

    # Use yt-dlp to search YouTube and extract video titles and IDs
    RESULTS=$(yt-dlp "ytsearch10:$SEARCH_TERM" --flat-playlist --print "%(id)s\t%(title)s" --quiet)

    # Check if no results are found
    if [ -z "$RESULTS" ]; then
        echo "No results found."
        return 1
    fi

    # Display the titles with index numbers
    echo "Search results:"
    echo "$RESULTS" | nl -s'. ' | cut -f2-

    # Allow the user to select a video or search again
    while true; do
        # Prompt user to select a video by index or exit
        echo "Enter the number of the video you want to play (or type 'r' to search again):"
        read -r SELECTION

        # If 'r' is entered, return to search again
        if [ "$SELECTION" == "r" ]; then
            return 1
        fi

        # Exit if no valid input is given
        if [ -z "$SELECTION" ] || ! echo "$SELECTION" | grep -q '^[0-9]*$'; then
            echo "Invalid selection."
            continue
        fi

        # Get the selected video ID
        VIDEO_ID=$(echo "$RESULTS" | sed -n "${SELECTION}p" | awk -F'\t' '{print $1}')

        # Construct the full YouTube URL
        VIDEO_URL="https://www.youtube.com/watch?v=$VIDEO_ID"

        # Play the selected video in mpv with 1080p preference
        mpv --ytdl-format="bestvideo[height<=720]+bestaudio/best[height<=720]" "$VIDEO_URL"

        # Ask if the user wants to select another video or exit
        echo "Do you want to select another video from the current search? (y/n)"
        read -r RESPONSE
        if [ "$RESPONSE" != "y" ]; then
            break
        fi
    done
}

# Main loop
while true; do
    # Call the search_and_play function
    search_and_play

    # Ask if the user wants to search for something else
    echo "Do you want to search for something else? (y/n)"
    read -r RESPONSE
    if [ "$RESPONSE" != "y" ]; then
        echo "Exiting script."
        break
    fi
done
