#!/usr/bin/env bash

# -------------------------------------------------------------------
#  VLC YouTube stream launcher with fullscreen and adaptive hardware acceleration
#  Designed for:
#    - Raspberry Pi 5 (V4L2 M2M + OpenGL ES)
#    - Old Intel/AMD desktops (VA-API → OpenGL → XVideo fallback)
#    - Any other machine (pure software playback)
#  Fix: force avformat demuxer to avoid "Failed to create demuxer (nil) TS"
#  Requires: yt-dlp, native VLC (system package, not Flatpak)
# -------------------------------------------------------------------

# ---------- YOUR STREAMS (order is preserved) ----------
STREAM_NAMES=(
    "CritterVision Critter Cam"
    "Woodlands Critter Quest"
    "Cornell Sapsucker Woods"
    "Cornell Panama Fruit Feeder"
    "Cornell Panama Hummingbird Feeder Cam at Canopy Tower"
    "Coffee Shop Radio Lo-Fi"
    "Chillhop Radio"
    "Chillhop Late Night Vibes"
    "Chillhop Beats to Relax to"
    "Bald Eagle Nest Cam"
)

STREAM_URLS=(
    "https://youtu.be/HlJ4aRtYhoo"
    "https://youtu.be/oI8R4_UG3Fs"
    "https://youtu.be/x10vL6_47Dw"
    "https://youtu.be/WtoxxHADnGk"
    "https://youtu.be/0xFARCdZ3vA"
    "https://youtu.be/blAFxjhg62k"
    "https://youtu.be/5yx6BWlEVcY"
    "https://youtu.be/i6WzngxTnBA"
    "https://youtu.be/7NOSDKb0HlU"
    "https://youtu.be/B4-L2nfGcuE"
)

# ---------- HELPER FUNCTIONS ----------
die() { echo "ERROR: $*" >&2; exit 1; }

# ---------- DEPENDENCY CHECK ----------
check_deps() {
    command -v yt-dlp >/dev/null || die "yt-dlp is required. Install with: pip install yt-dlp"
    command -v vlc   >/dev/null || die "Native VLC is required. Install with: sudo apt install vlc"
}

# ---------- PLATFORM DETECTION ----------
detect_platform() {
    if [ -f /proc/device-tree/model ]; then
        local model
        model=$(tr -d '\0' < /proc/device-tree/model)
        if [[ "$model" == *"Raspberry Pi"* ]]; then
            echo "pi"
            return
        fi
    fi
    echo "desktop"
}

# ---------- STREAM SELECTION (menus to stderr) ----------
choose_stream() {
    echo "Select a YouTube stream:" >&2
    echo "------------------------" >&2

    local i=1
    for name in "${STREAM_NAMES[@]}"; do
        echo "  $i) $name" >&2
        ((i++))
    done

    local other_index=$i
    echo "  $i) Other (paste your own URL)" >&2

    while true; do
        read -rp "Enter number (1-$i): " choice
        if [[ "$choice" =~ ^[0-9]+$ ]] && ((choice >= 1 && choice <= i)); then
            if [ "$choice" -eq "$other_index" ]; then
                read -rp "Paste the YouTube URL: " stream_url
                [ -z "$stream_url" ] && die "No URL provided."
                echo "$stream_url"
            else
                echo "${STREAM_URLS[$((choice-1))]}"
            fi
            break
        else
            echo "Invalid choice. Please enter a number between 1 and $i." >&2
        fi
    done
}

# ---------- RESOLUTION SELECTION ----------
choose_resolution() {
    echo "" >&2
    echo "Select resolution:" >&2
    echo "  1) 480p" >&2
    echo "  2) 720p" >&2
    echo "  3) 1080p" >&2

    while true; do
        read -rp "Enter 1, 2, or 3: " res
        case "$res" in
            1) echo "480"; return ;;
            2) echo "720"; return ;;
            3) echo "1080"; return ;;
            *) echo "Invalid. Please enter 1, 2, or 3." >&2 ;;
        esac
    done
}

# ---------- VIDEO OUTPUT FALLBACK TEST (used for desktop) ----------
# Returns the first working VLC video output module from a list.
test_vout() {
    for vout in "$@"; do
        if vlc --no-audio --no-video-title-show --vout="$vout" --play-and-exit --intf=dummy vlc://quit &>/dev/null; then
            echo "$vout"
            return 0
        fi
    done
    return 1
}

# ---------- LAUNCH VLC ----------
launch_vlc() {
    local url="$1"
    local res="$2"
    local platform="$3"

    # Fetch the best combined video+audio stream up to the chosen height
    local ytformat="best[height<=${res}]"
    local stream_url
    echo "Fetching stream URL with yt-dlp..."
    stream_url=$(yt-dlp -f "$ytformat" -g "$url") || die "yt-dlp failed to extract stream URL."

    # Base VLC options – always fullscreen, one instance, close when stream ends.
    # Force avformat demuxer to avoid "adaptive demux error: Failed to create demuxer (nil) TS"
    local vlc_opts=(
        --fullscreen
        --one-instance
        --play-and-exit
        --demux=avformat
    )

    # Hardware decoding & output selection
    if [ "$platform" = "pi" ]; then
        # --- Raspberry Pi optimisations ---
        vlc_opts+=(--avcodec-hw=v4l2m2m --vout=gles2)
        echo "Using Raspberry Pi acceleration: v4l2m2m + gles2"

    else
        # --- Desktop / old hardware ---
        # 1. Try VA-API hardware decoding if available
        if vainfo &>/dev/null; then
            vlc_opts+=(--avcodec-hw=vaapi)
            echo "VA-API hardware decoding enabled."
        else
            echo "VA-API not available – falling back to software decoding."
        fi

        # 2. Pick the best video output module automatically
        local vout
        vout=$(test_vout gl xcb_xv xcb_x11) || die "No working VLC video output found (tried gl, xcb_xv, xcb_x11)."
        vlc_opts+=(--vout="$vout")
        echo "Selected video output: $vout"
    fi

    echo ""
    echo "Launching: vlc ${vlc_opts[*]} <stream>"
    vlc "${vlc_opts[@]}" "$stream_url"
}

# ---------- MAIN ----------
check_deps

# Ensure stream arrays match
if [ ${#STREAM_NAMES[@]} -ne ${#STREAM_URLS[@]} ]; then
    die "Number of stream names and URLs do not match."
fi

platform=$(detect_platform)
if [ "$platform" = "pi" ]; then
    echo "Detected Raspberry Pi – using V4L2 M2M + OpenGL ES output."
else
    echo "Detected desktop / laptop – will select best available acceleration."
fi
echo ""

stream_url=$(choose_stream)
resolution=$(choose_resolution)

launch_vlc "$stream_url" "$resolution" "$platform"
