#!/bin/bash

# Run waybar-mpris for a short time to capture a single output and exit
TRACK_INFO=$(timeout 0.1 waybar-mpris --position --autofocus)

# Check if TRACK_INFO is valid and non-empty
if [[ -z "$TRACK_INFO" ]]; then
    echo "Error: No track information received." >&2
    exit 1  # Exit silently if no track information is available
fi

# Remove any control characters and trailing whitespace
CLEAN_TRACK_INFO=$(echo "$TRACK_INFO" | tr -d '\000-\011\013\014\016-\037' | sed 's/[[:space:]]*$//')

# Debug print: Check the cleaned TRACK_INFO after initial sanitization
echo "Sanitized TRACK_INFO: '$CLEAN_TRACK_INFO'"

# Use `jq` to extract the `text` field from the cleaned JSON
TEXT=$(echo "$CLEAN_TRACK_INFO" | jq -r '.text')

# If TEXT extraction fails, print error and exit
if [[ -z "$TEXT" ]]; then
    echo "Error: Failed to extract 'text' field from JSON. Check if TRACK_INFO is valid."
    echo "$CLEAN_TRACK_INFO" | od -c  # Print raw hex output for debugging
    exit 1
fi

# Remove the specific `` symbol using its Unicode representation (\xEF\xA3\xA3) and trim leading spaces
TEXT_CLEANED=$(echo "$TEXT" | sed 's/\xEF\xA3\xA3//g' | sed 's/^[[:space:]]*//')

# Debug print: Check the TEXT after removing `` and trimming spaces
echo "Cleaned TEXT: '$TEXT_CLEANED'"

# If TEXT_CLEANED is empty, it means the player is paused or has no metadata
if [[ -z "$TEXT_CLEANED" ]]; then
    # Output an empty JSON with placeholders
    echo '{"artist": "", "album": "", "title": ""}'
    exit 0
fi

# Use `awk` to extract artist, album, and title using a consistent separator
ARTIST=$(echo "$TEXT_CLEANED" | awk -F' - ' '{print $1}')
ALBUM=$(echo "$TEXT_CLEANED" | awk -F' - ' '{print $2}')
TITLE=$(echo "$TEXT_CLEANED" | awk -F' - ' '{print $3}' | sed 's/([^()]*)$//')  # Remove time info in parentheses

# Debug print: Check the extracted values for ARTIST, ALBUM, and TITLE
echo "Extracted ARTIST: '$ARTIST'"
echo "Extracted ALBUM: '$ALBUM'"
echo "Extracted TITLE: '$TITLE'"

# Check if artist, album, and title are non-empty
if [[ -z "$ARTIST" || -z "$ALBUM" || -z "$TITLE" ]]; then
    echo "Error: Could not extract artist, album, or title from the cleaned text." >&2
    # Output an empty JSON with placeholders
    echo '{"artist": "", "album": "", "title": ""}'
    exit 0
fi

# Construct a JSON object for Waybar using `jq`
TRACK_JSON=$(jq -n --arg artist "$ARTIST" --arg album "$ALBUM" --arg title "$TITLE" \
                '{artist: $artist, album: $album, title: $title}')

# Debug print: Check the final constructed JSON
echo "Generated TRACK_JSON: '$TRACK_JSON'"

# Output the final JSON for Waybar, ensuring proper newline at the end
echo "$TRACK_JSON"


