#!/bin/bash

CONF="$HOME/.config/clickradio"

# Function to sanitize station names for filesystem safety
sanitize_filename() {
  echo "$1" | sed \
    -e 's/[\/:*?"<>|]/_/g' \
    -e 's/^[ \t]*//;s/[ \t]*$//' \
    -e 's/  */ /g'
}

# Function to escape HTML characters (for use in popups, if needed)
escape_html() {
  echo "$1" | sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g'
}

# Read first line from $CONF/playing
read -r FIRST_LINE < "$CONF/playing"

# Extract raw station name from span
RAW_STATION=$(echo "$FIRST_LINE" | grep -oP '(?<=>).*?(?=</span>)')

# Sanitize for filename usage
STATION=$(sanitize_filename "$RAW_STATION")

# Determine the actual extension (.m3u or .pls)
if [ -f "$CONF/slist/$STATION.m3u" ]; then
    EXT="m3u"
elif [ -f "$CONF/slist/$STATION.pls" ]; then
    EXT="pls"
else
    echo "Error: Cannot determine extension for '$STATION'"
    exit 1
fi

# Compose final filename
FILENAME="${STATION}.${EXT}"

# Save to .fav
echo "$FILENAME" > "$CONF/.fav"

# If not already in favorites, copy it and trigger notification
if [ ! -f "$CONF/favs/$FILENAME" ]; then
cp -r "$CONF/slist/$FILENAME" "$CONF/favs"
python3 /usr/share/click-radio/menu/notify/fav_stream_add.py
else
python3 /usr/share/click-radio/menu/notify/fav_stream_exists.py
fi
