#!/usr/bin/env bash
# hu.sh — listen to podcasts, radio, and music files
# Pure discovery via public directories.

# File paths for your plaintext databases
FEED_DB="$HOME/.pod_feeds"
RADIO_DB="$HOME/.radio_feeds"
touch "$FEED_DB" "$RADIO_DB"

# Colours (Graceful degradation)
if [ -t 1 ] && command -v tput >/dev/null 2>&1; then
    GREEN='\033[0;32m'
    BLUE='\033[0;34m'
    YELLOW='\033[1;33m'
    CYAN='\033[0;36m'
    NC='\033[0m'
else
    GREEN='' BLUE='' YELLOW='' CYAN='' NC=''
fi

log_status() { echo -e "${BLUE}[*]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_error() { echo -e "${YELLOW}[!]${NC} $1"; }

# -------------------------------------------------------------
# 1. PODCAST WORKFLOWS (Discovery via iTunes Public Catalog)
# -------------------------------------------------------------
list_pods() {
    clear
    echo -e "${BLUE}=== Saved Podcasts ===${NC}"
    if [ ! -s "$FEED_DB" ]; then log_error "No saved podcasts yet. Use Option 2 to find some!"; return 1; fi
    local i=1
    while IFS=$'\t' read -r name url; do
        echo -e "${GREEN}[$i]${NC} $name"
        i=$((i+1))
    done < "$FEED_DB"
    return 0
}

browse_pod_episodes() {
    list_pods || return
    echo -n "Select a podcast (or 'q' to go back): " && read -r choice
    [[ "$choice" == "q" || -z "$choice" ]] && return
    local target; target=$(sed -n "${choice}p" "$FEED_DB")
    [ -z "$target" ] && { log_error "Invalid selection."; return; }

    local name; name=$(echo "$target" | cut -f1)
    local url; url=$(echo "$target" | cut -f2)

    log_status "Fetching episodes for $name..."
    local xml; xml=$(curl -sL "$url")

    local -a titles=()
    local -a urls=()

    # Portable XML stream extraction (Bash 3.2+ compliant)
    while read -r line; do titles+=("$line"); done < <(echo "$xml" | grep -oE '<title>[^<]+' | sed 's/<title>//' | tail -n +2 | head -n 25)
    while read -r line; do urls+=("$line"); done < <(echo "$xml" | grep -oE '<enclosure[^>]+url=["'\''][^"'\'']+' | sed -E 's/<enclosure.+url=["'\'']//' | head -n 25)

    while true; do
        clear
        echo -e "${BLUE}=== $name ===${NC}"
        for i in "${!titles[@]}"; do echo -e "${GREEN}[$((i+1))]${NC} ${titles[$i]}"; done
        echo -n "Select episode to play (or 'q' to go back): " && read -r ep_choice
        [[ "$ep_choice" == "q" || -z "$ep_choice" ]] && break
        local idx=$((ep_choice-1))
        if [[ -n "${urls[$idx]}" ]]; then
            log_success "Playing: ${titles[$idx]}"
            mpv --no-video "${urls[$idx]}"
        else
            log_error "Invalid selection."; sleep 1
        fi
    done
}

search_podcasts() {
    clear; echo -e "${BLUE}=== Search Online Podcasts ===${NC}"
    echo -n "Search query (e.g. Daily Stoic, Lex Fridman): " && read -r query
    [ -z "$query" ] && return
    local encoded; encoded=$(echo "$query" | tr ' ' '+')

    log_status "Searching public iTunes catalog..."
    local json; json=$(curl -sL "https://itunes.apple.com/search?term=${encoded}&media=podcast&limit=10")

    local -a names=()
    local -a feeds=()
    while read -r line; do names+=("$line"); done < <(echo "$json" | grep -oE '"collectionName":"[^"]+"' | sed 's/"collectionName":"//;s/"//g')
    while read -r line; do feeds+=("$line"); done < <(echo "$json" | grep -oE '"feedUrl":"[^"]+"' | sed 's/"feedUrl":"//;s/"//g')

    if [ ${#names[@]} -eq 0 ]; then log_error "No results found."; return; fi

    clear
    echo -e "${BLUE}=== Search Results for '$query' ===${NC}"
    for i in "${!names[@]}"; do echo -e "${GREEN}[$((i+1))]${NC} ${names[$i]}"; done
    echo -n "Enter number to save podcast (or 'q' to cancel): " && read -r sub_choice
    [[ "$sub_choice" == "q" || -z "$sub_choice" ]] && return
    local s_idx=$((sub_choice-1))
    if [[ -n "${feeds[$s_idx]}" ]]; then
        echo -e "${names[$s_idx]}\t${feeds[$s_idx]}" >> "$FEED_DB"
        log_success "Successfully saved ${names[$s_idx]}!"
    fi
}

# -------------------------------------------------------------
# 2. INTERNET RADIO WORKFLOWS (Discovery via Radio-Browser API)
# -------------------------------------------------------------
list_radio() {
    clear
    echo -e "${BLUE}=== Saved Radio Stations ===${NC}"
    if [ ! -s "$RADIO_DB" ]; then log_error "No saved radio stations yet. Use Option 4 to find some!"; return 1; fi
    local i=1
    while IFS=$'\t' read -r name url; do echo -e "${GREEN}[$i]${NC} $name"; i=$((i+1)); done < "$RADIO_DB"
    return 0
}

play_radio() {
    list_radio || return
    echo -n "Select station to play (or 'q' to go back): " && read -r choice
    [[ "$choice" == "q" || -z "$choice" ]] && return
    local target; target=$(sed -n "${choice}p" "$RADIO_DB")
    if [[ -n "$target" ]]; then
        local name; name=$(echo "$target" | cut -f1)
        local url; url=$(echo "$target" | cut -f2)
        log_success "Streaming Live Radio: $name"
        mpv --no-video "$url"
    fi
}

search_radio_stations() {
    clear; echo -e "${BLUE}=== Global Live Radio Search ===${NC}"
    echo -n "Enter station name, genre, or keyword (e.g. Top 40, Jazz, BBC): " && read -r query
    [ -z "$query" ] && return
    local encoded; encoded=$(echo "$query" | tr ' ' '+')

    log_status "Querying global radio-browser database..."
    local json; json=$(curl -sL "https://de1.api.radio-browser.info/json/stations/byname/${encoded}?limit=10")

    local -a names=()
    local -a urls=()
    while read -r line; do names+=("$line"); done < <(echo "$json" | grep -oE '"name":"[^"]+"' | sed 's/"name":"//;s/"//g')
    while read -r line; do urls+=("$line"); done < <(echo "$json" | grep -oE '"url_resolved":"[^"]+"' | sed 's/"url_resolved":"//;s/"//g')

    if [ ${#names[@]} -eq 0 ]; then log_error "No stations found."; return; fi

    clear
    echo -e "${BLUE}=== Search Results for '$query' ===${NC}"
    for i in "${!names[@]}"; do echo -e "${GREEN}[$((i+1))]${NC} ${names[$i]}"; done
    echo -n "Enter number to save station (or 'q' to cancel): " && read -r r_choice
    [[ "$r_choice" == "q" || -z "$r_choice" ]] && return
    local r_idx=$((r_choice-1))
    if [[ -n "${urls[$r_idx]}" ]]; then
        echo -e "${names[$r_idx]}\t${urls[$r_idx]}" >> "$RADIO_DB"
        log_success "Saved ${names[$r_idx]} to your personal lineup!"
    fi
}

# -------------------------------------------------------------
# 3. LOCAL FILE PLAYBACK WORKFLOWS
# -------------------------------------------------------------
play_local_media() {
    clear
    echo -e "${BLUE}=== Local Media File Browser ===${NC}"
    echo -n "Enter path to file or directory (Default: current dir): " && read -r loc_path
    local target="${loc_path:-.}"

    target="${target/#\~/$HOME}"

    if [ -f "$target" ]; then
        log_success "Playing local file: $(basename "$target")"
        mpv --no-video "$target"
    elif [ -d "$target" ]; then
        while true; do
            clear
            echo -e "${BLUE}=== Directory: $target ===${NC}"

            local -a files=()
            while read -r line; do
                [[ -n "$line" ]] && files+=("$line")
            done < <(find "$target" -maxdepth 1 -type f \( -name "*.mp3" -o -name "*.m4a" -o -name "*.wav" -o -name "*.flac" -o -name "*.ogg" \) | sort)

            if [ ${#files[@]} -eq 0 ]; then
                log_error "No audio files found in this directory."
                echo "Press any key to return..." && read -n 1 && return
            fi

            for i in "${!files[@]}"; do
                echo -e "${GREEN}[$((i+1))]${NC} $(basename "${files[$i]}")"
            done
            echo -e "${CYAN}[a]${NC} Play ALL files sequentially as a playlist"
            echo -n "Select track option (or 'q' to go back): " && read -r file_choice
            [[ "$file_choice" == "q" || -z "$file_choice" ]] && break

            if [[ "$file_choice" == "a" ]]; then
                log_success "Queuing full directory into mpv..."
                mpv --no-video "${files[@]}"
            else
                local f_idx=$((file_choice-1))
                if [[ -n "${files[$f_idx]}" ]]; then
                    log_success "Playing: $(basename "${files[$f_idx]}")"
                    mpv --no-video "${files[$f_idx]}"
                fi
            fi
        done
    else
        log_error "Path does not exist."
        sleep 1
    fi
}

# -------------------------------------------------------------
# MAIN APP ROUTER
# -------------------------------------------------------------
while true; do
    echo -e "\n${BLUE}=== Terminal Audio Hub ===${NC}"
    echo "1) Browse / Play Saved Podcasts"
    echo "2) Search Online Podcasts"
    echo "3) Browse / Play Saved Radio Stations"
    echo "4) Search Global Live Radio"
    echo "5) Play Local Media (File/Directory)"
    echo "6) Exit"
    echo -n "Select option: " && read -r main_opt

    case "$main_opt" in
        1) browse_pod_episodes ;;
        2) search_podcasts ;;
        3) play_radio ;;
        4) search_radio_stations ;;
        5) play_local_media ;;
        6) log_status "Exiting Hub. See you later."; exit 0 ;;
        *) log_error "Invalid selection." ;;
    esac
done
