import os
import requests
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Set up Spotipy with authentication
scope = "user-read-currently-playing user-read-playback-state"
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
    client_id=os.getenv('SPOTIPY_CLIENT_ID'),
    client_secret=os.getenv('SPOTIPY_CLIENT_SECRET'),
    redirect_uri=os.getenv('SPOTIPY_REDIRECT_URI'),
    scope=scope
))

# Get the currently playing track information
response = sp.current_playback()

# Discord webhook URL
discord_webhook_url = os.getenv('DISCORD_WEBHOOK_URL')

# Check if a track is currently playing
if response is not None and response.get('is_playing', False):
    track = response['item']
    track_name = track['name']
    album_name = track['album']['name']
    artists = ', '.join([artist['name'] for artist in track['artists']])
    album_art_url = track['album']['images'][0]['url']
    track_url = track['external_urls']['spotify']

    # Initialize playlist_url
    playlist_url = None

    # Check if the track is from a context (playlist)
    if response.get('context') and response['context'].get('type') == 'playlist':
        playlist_uri = response['context']['uri']
        playlist_id = playlist_uri.split(':')[-1]
        playlist = sp.playlist(playlist_id)
        playlist_name = playlist['name']
        playlist_url = playlist['external_urls']['spotify']

    # Format the message
    description = f"**Artists**\n{artists}\n**Album**\n{album_name}\n\n[Listen on Spotify]({track_url})"
    if playlist_name and playlist_url:
        description += f" |  [{playlist_name}]({playlist_url})"

    message = {
        "embeds": [
            {
                "title": track_name,
                "description": description,
                "thumbnail": {"url": album_art_url}
            }
        ]
    }

    # Send the message to the Discord webhook
    response = requests.post(discord_webhook_url, json=message)

    if response.status_code == 204:
        print("Message sent to Discord successfully.")
    else:
        print(f"Failed to send message to Discord. Status code: {response.status_code}")
else:
    print("No track is currently playing.")