#!/bin/bash

#set -x  # Activa el modo de depuración

# Paths y archivos temporales
CURRENT_TRACK_FILE="/tmp/current_track.txt"
LYRICS_FILE="/tmp/lyrics.txt"
LOG_FILE="/tmp/lyrics_error.log"
STATE_FILE="/tmp/lyrics_state.txt"

# Función para limpiar el título de la canción
clean_title() {
    local title="$1"
    # Eliminar prefijos como "B3 ", "A1 ", etc.
    title=$(echo "$title" | sed -E 's/^[A-Za-z0-9]{1,3}[[:space:]]+//')
    # Eliminar caracteres especiales como "$", "#", etc.
    title=$(echo "$title" | tr -d '$#@!%^&*()[]{}<>?/\\|`~')
    # Eliminar espacios adicionales al inicio y al final
    title=$(echo "$title" | sed 's/^ *//;s/ *$//')
    echo "$title"
}

# Obtener información de la pista actual
TRACK_INFO=$(playerctl metadata --format "{{artist}} - {{title}}" 2>>"$LOG_FILE")
STATUS=$(playerctl status 2>>"$LOG_FILE")
echo "STATUS: '$STATUS'" >> "$LOG_FILE"

# Si no hay información de pista o el estado no es 'Playing', salimos
if [ -z "$TRACK_INFO" ] || [ "$STATUS" != "Playing" ]; then
    jq -c -n '{"text":"","tooltip":""}'
    exit 0
fi

echo "TRACK_INFO: '$TRACK_INFO'" >> "$LOG_FILE"

if [ -z "$TRACK_INFO" ]; then
    echo "No track info available" > "$LYRICS_FILE"
    exit 1
fi

# Extraer artista y título
ARTIST=$(echo "$TRACK_INFO" | cut -d '-' -f 1 | sed 's/^ *//;s/ *$//')
TITLE=$(echo "$TRACK_INFO" | cut -d '-' -f 2- | sed 's/^ *//;s/ *$//')

echo "ARTIST: '$ARTIST'" >> "$LOG_FILE"
echo "TITLE Original: '$TITLE'" >> "$LOG_FILE"

# Limpiar el título de la canción
CLEAN_TITLE=$(clean_title "$TITLE")
echo "TITLE Limpio: '$CLEAN_TITLE'" >> "$LOG_FILE"

# Verificar si la pista ha cambiado
if [ "$TRACK_INFO" != "$(cat "$CURRENT_TRACK_FILE" 2>/dev/null)" ]; then
    echo "$TRACK_INFO" > "$CURRENT_TRACK_FILE"

    # Obtener letras usando el script Python
    lyrics=$(python3 ~/.config/waybar/scripts/get_lyrics.py "$ARTIST" "$CLEAN_TITLE" 2>>"$LOG_FILE")

    echo "lyrics: '$lyrics'" >> "$LOG_FILE"

    if [[ "$lyrics" == "Letras no encontradas." ]]; then
        lyrics="Letras no encontradas para $ARTIST - $CLEAN_TITLE"
    fi

    echo "$lyrics" > "$LYRICS_FILE"
else
    lyrics=$(cat "$LYRICS_FILE")
fi

# Leer el estado
if [ -f "$STATE_FILE" ]; then
    STATE=$(cat "$STATE_FILE")
else
    STATE="full"
fi

# Ajustar las letras según el estado
if [ "$STATE" = "second_half" ]; then
    total_lines=$(echo "$lyrics" | wc -l)
    half_line=$(( (total_lines + 1) / 2 ))
    lyrics=$(echo "$lyrics" | tail -n +$half_line)
fi

# Verificar si el player activo es Firefox
PLAYER_NAME=$(playerctl -a metadata --format '{{playerName}}' 2>>"$LOG_FILE" | head -n 1)
echo "PLAYER_NAME: '$PLAYER_NAME'" >> "$LOG_FILE"

if [[ "$PLAYER_NAME" == "firefox" ]]; then
    jq -c -n '{"text":"","tooltip":""}'
    exit 0
fi

# Generar JSON para Waybar
jq -c -n --arg text "🎵" --arg tooltip "$lyrics" '{"text":$text,"tooltip":$tooltip}'

