#!/usr/bin/env python3
import subprocess
import json
import lyricsgenius

# Reemplaza con tu token de Genius
GENIUS_API_TOKEN = "wl-5tHeP4k1CS7Y_HbhN7QYDcEvFZ89nDZUX9ddpN90pvOmfgu-zAFsFHrFUBaGg"

# Comando para obtener la información del track actual con waybar-mpris
def get_mpris_info():
    try:
        # Ejecutar `waybar-mpris` y obtener la salida
        mpris_output = subprocess.check_output(
            ["waybar-mpris", "--position", "--autofocus", "--order", "ARTIST:TITLE:POSITION"], 
            universal_newlines=True
        ).strip()
        
        # Analizar la salida de `waybar-mpris`
        artist, title, position = mpris_output.split(" - ")
        return {"artist": artist, "title": title, "position": position}
    except subprocess.CalledProcessError:
        return None

# Obtener las letras de la canción usando lyricsgenius
def get_lyrics(artist, title):
    genius = lyricsgenius.Genius(GENIUS_API_TOKEN)
    try:
        song = genius.search_song(title, artist)
        return song.lyrics if song else "Lyrics not found"
    except Exception as e:
        return f"Error fetching lyrics: {e}"

# Ejecutar el script
def main():
    # Obtener la información del track actual
    mpris_info = get_mpris_info()
    if mpris_info:
        artist = mpris_info.get("artist", "")
        title = mpris_info.get("title", "")
        position = mpris_info.get("position", "")

        # Obtener las letras
        lyrics = get_lyrics(artist, title)

        # Crear el JSON con la información del track y las letras
        output = {
            "artist": artist,
            "title": title,
            "position": position,
            "lyrics": lyrics
        }
        print(json.dumps(output))
    else:
        print(json.dumps({"status": "stopped", "lyrics": "No song playing"}))

if __name__ == "__main__":
    main()

