import requests
import json
import sys
from urllib.parse import quote

def fetch_lyrics(artist, title):
    """Fetch lyrics for the given artist and track title."""
    base_url = f"https://api.lyrics.ovh/v1/{quote(artist)}/{quote(title)}"
    try:
        response = requests.get(base_url)
        if response.status_code == 200:
            data = response.json()
            return data.get("lyrics", "Lyrics not found.")
        else:
            return "Lyrics not found."
    except Exception as e:
        return f"Error fetching lyrics: {e}"

def main():
    if len(sys.argv) < 3:
        print("Usage: fetch_lyrics.py <artist> <title>")
        sys.exit(1)

    artist = sys.argv[1]
    title = sys.argv[2]

    lyrics = fetch_lyrics(artist, title)
    # Escape newlines for tooltip display
    escaped_lyrics = lyrics.replace("\n", "\\n")
    
    # Output lyrics in JSON format for waybar-mpris
    print(json.dumps({"tooltip": escaped_lyrics}))

if __name__ == "__main__":
    main()

