import subprocess
import requests
import os

# --- CONFIGURATION ---
# Use the playlist URL you verified works
PLAYLIST_ID = '1282495565' 
HISTORY_FILE = 'downloaded_albums.txt'
# ---------------------

def get_playlist_albums(playlist_id):
    url = f"https://api.deezer.com/playlist/{playlist_id}/tracks"
    albums = {}
    
    response = requests.get(url).json()
    
    if 'data' not in response:
        print("Error: Could not retrieve playlist. Is it set to public?")
        return albums

    for track in response['data']:
        album_id = track['album']['id']
        album_title = track['album']['title']
        # Construct the direct album URL
        album_url = f"https://www.deezer.com/album/{album_id}"
        albums[album_id] = {'title': album_title, 'url': album_url}
        
    return albums

# 1. Load history to avoid re-downloading
if os.path.exists(HISTORY_FILE):
    with open(HISTORY_FILE, 'r') as f:
        history = set(f.read().splitlines())
else:
    history = set()

# 2. Get the albums from the playlist
print(f"Checking Deezer playlist {PLAYLIST_ID} for albums...")
target_albums = get_playlist_albums(PLAYLIST_ID)
print(f"Found {len(target_albums)} unique albums in the playlist.")

# 3. Download them
for alb_id, info in target_albums.items():
    if str(alb_id) not in history:
        print(f"\n--- Downloading Album: {info['title']} ---")
        
        # Run the rip command for the ALBUM url
        process = subprocess.run(['rip', '--quality', '0', 'url', info['url']])
        
        if process.returncode == 0:
            with open(HISTORY_FILE, 'a') as f:
                f.write(str(alb_id) + '\n')
            history.add(str(alb_id))
            print(f"Finished: {info['title']}")
    else:
        # We skip it because it's already in the history file
        pass

print("\nAll new albums processed.")
