import urllib.parse
from pathlib import Path

def process_mp3s(directory=".", m3u_filename="playlist.m3u"):
    dir_path = Path(directory)
    
    # Verify the directory exists
    if not dir_path.is_dir():
        print(f"Error: The directory '{directory}' does not exist.")
        return

    # Gather all .mp3 files in the directory
    mp3_files = [f for f in dir_path.iterdir() if f.is_file() and f.suffix.lower() == '.mp3']
    
    if not mp3_files:
        print(f"No MP3 files found in '{directory}'.")
        return

    # Sort alphabetically for a neat playlist
    mp3_files.sort(key=lambda x: x.name)

    print("--- Copy the text below into Discord ---")
    
    # Open the .m3u file for writing
    with open(dir_path / m3u_filename, "w", encoding="utf-8") as m3u_file:
        for file_path in mp3_files:
            filename = file_path.name
            
            # Write the raw filename to the .m3u file
            m3u_file.write(f"{filename}\n")
            
            # Derive song name: extract the name without extension (.stem) and replace underscores
            song_name = file_path.stem.replace('_', ' ')
            
            # URL encode the filename so the link doesn't break in Discord
            encoded_filename = urllib.parse.quote(filename)
            
            # Print the formatted Discord string with the updated URL
            print(f"{song_name}: https://music.phat.wtf/{encoded_filename}")

    print("----------------------------------------")
    print(f"\nSuccess: '{m3u_filename}' created with {len(mp3_files)} tracks.")

if __name__ == "__main__":
    # Specify your target directory here. "." means the current folder the script is in.
    target_dir = "." 
    process_mp3s(target_dir)
