import requests
import json
import subprocess
import os

# Replace with your Last.fm API key
#API_KEY = 'c21b81ac4e50adcd49d36caad2c4bcf2'
API_KEY = 'd6cbcf9e6b4d77da1dcb91461020bc37'
USER = 'terafl0p5'
ALBUM_ART_PATH = "/tmp/waybar-mediaplayer-art"
STATE_FILE = "/tmp/waybar_now_playing_state.txt"

def get_now_playing(api_key, user):
    url = 'http://ws.audioscrobbler.com/2.0/'
    params = {
        'method': 'user.getrecenttracks',
        'user': user,
        'api_key': api_key,
        'format': 'json',
        'limit': 1
    }
    
    response = requests.get(url, params=params)
    data = response.json()
    
    if 'recenttracks' in data and 'track' in data['recenttracks']:
        tracks = data['recenttracks']['track']
        if len(tracks) > 0:
            now_playing = tracks[0]
            # Check if the track is currently being played
            if '@attr' in now_playing and now_playing['@attr'].get('nowplaying') == 'true':
                artist = now_playing['artist']['#text']
                track = now_playing['name']
                album = now_playing['album']['#text']

                # Get album cover URL (largest available size)
                album_cover_url = ""
                if 'image' in now_playing and len(now_playing['image']) > 0:
                    album_cover_url = now_playing['image'][-1]['#text']  # Last image is usually the largest

                # Download the album cover image if URL is available
                if album_cover_url:
                    try:
                        image_response = requests.get(album_cover_url)
                        with open(ALBUM_ART_PATH, 'wb') as img_file:
                            img_file.write(image_response.content)
                    except Exception as e:
                        print(f"Error downloading album cover: {e}")

                # Run the bitrate script and capture its output
                try:
                    bitrate = subprocess.check_output(
                        ["/home/teraflops/.local/bin/show_rate3.sh"], 
                        text=True
                    ).strip()  # Adjust the path as needed
                except subprocess.CalledProcessError:
                    bitrate = "Unknown bitrate"

                # Combine track info with bitrate
                track_info = f"{artist} - {track} [{bitrate}]"
                
                # Tooltip with album information
                tooltip = f"Artist: {artist}\nTrack: {track}\nAlbum: {album}\nBitrate: {bitrate}"

                # Read current click state from temporary file
                if os.path.exists(STATE_FILE):
                    with open(STATE_FILE, 'r') as file:
                        state = file.read().strip()
                else:
                    state = "show"  # Default state shows details

                # Show icon if the state is "hide"
                if state == "hide":
                    print(json.dumps({
                        "text": "🎵",
                        "tooltip": tooltip,
                        "class": "rate"
                    }))
                else:
                    # Output in JSON format for Waybar
                    print(json.dumps({
                        "text": track_info,
                        "tooltip": tooltip,
                        "class": "custom-rate"
                    }))
            else:
                # No track is playing, remove the album art
                if os.path.exists(ALBUM_ART_PATH):
                    os.remove(ALBUM_ART_PATH)
        else:
            # No recent tracks found, remove the album art
            if os.path.exists(ALBUM_ART_PATH):
                os.remove(ALBUM_ART_PATH)
    else:
        # Error fetching data from Last.fm, remove the album art
        if os.path.exists(ALBUM_ART_PATH):
            os.remove(ALBUM_ART_PATH)

def toggle_display_state():
    # Toggle between showing details and showing only the icon
    if os.path.exists(STATE_FILE):
        with open(STATE_FILE, 'r') as file:
            state = file.read().strip()
        new_state = "hide" if state == "show" else "show"
    else:
        new_state = "hide"
    
    with open(STATE_FILE, 'w') as file:
        file.write(new_state)

# Determine if we're in normal mode or click mode
if __name__ == "__main__":
    import sys
    if len(sys.argv) > 1 and sys.argv[1] == "toggle":
        toggle_display_state()
    else:
        get_now_playing(API_KEY, USER)

os.system("pkill -RTMIN+15 waybar")

