import yt_dlp
import os
import re

def clean_filename(title):
    # Remove quotes and illegal characters
    title = title.strip("'").strip('"')
    return re.sub(r'[\\/*?:"<>|]', "", title)

def download_mp3(url, quality='320'):
    print(f"\n🔍 Processing: {url}")
    
    # 1. Fetch Title First (Clean Name)
    try:
        with yt_dlp.YoutubeDL({'quiet':True}) as ydl:
            info = ydl.extract_info(url, download=False)
            if 'entries' in info:
                title = '%(title)s' # Playlist default
            else:
                title = clean_filename(info['title'])
                print(f"📝 Renaming to: {title}")
    except Exception as e:
        print(f"❌ Error fetching info: {e}")
        return {"success": False, "error": "Invalid URL or video unavailable"}

    # 2. Download Options (adjustable quality)
    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': quality,
        }],
        'outtmpl': f'music/{title}.%(ext)s',
        'quiet': False,
        'no_warnings': True,
    }

    try:
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            ydl.download([url])
            print("✅ Success! (Hit Refresh in the App)")
            return {"success": True, "title": title}
    except Exception as e:
        print(f"❌ Error: {e}")
        return {"success": False, "error": str(e)}

if __name__ == "__main__":
    if not os.path.exists("music"):
        os.makedirs("music")

    print("--- TECHDJ DOWNLOADER (320kbps) ---")
    while True:
        url = input("\n🔗 URL (q to quit): ").strip()
        if url.lower() == 'q': break
        if url: download_mp3(url)
