import os
import subprocess
import wmi
import time
import re
import tempfile

VLC_PATH = r"C:\Program Files\VideoLAN\VLC\vlc.exe"

def get_sort_key(filename):
    """
    Extracts the leading number for numerical sorting.
    Handles '1 song', '10 song', '2 song' correctly.
    """
    # Look for any digit(s) at the very start of the filename
    match = re.match(r'^(\d+)', filename)
    if match:
        # Converting to int ensures 2 comes before 12
        return int(match.group(1))
    return 999999 

def play_in_vlc(drive_letter):
    print(f"Scanning {drive_letter} for MP3s...")
    mp3_paths = []
    
    for root, dirs, files in os.walk(drive_letter):
        for file in files:
            if file.lower().endswith(".mp3"):
                mp3_paths.append(os.path.join(root, file))
    
    if not mp3_paths:
        return None

    # SORTING LOGIC:
    # This sorts by the integer value of the leading number.
    mp3_paths.sort(key=lambda x: get_sort_key(os.path.basename(x)))

    with tempfile.NamedTemporaryFile(mode='w', suffix='.m3u', delete=False) as f:
        for path in mp3_paths:
            f.write(path + '\n')
        playlist_path = f.name

    print(f"Playing {len(mp3_paths)} files in numerical order.")
    return subprocess.Popen([VLC_PATH, playlist_path])

def monitor_drive():
    c = wmi.WMI()
    watcher = c.Win32_LogicalDisk.watch_for("creation")
    vlc_process = None
    
    print("System active. Waiting for CD...")
    
    while True:
        try:
            # Short timeout allows us to check for ejection frequently
            new_drive = watcher(timeout_ms=2000)
            if new_drive.DriveType == 4:
                drive_path = f"{new_drive.DeviceID}\\"
                time.sleep(3) 
                
                if vlc_process and vlc_process.poll() is None:
                    vlc_process.terminate()
                
                vlc_process = play_in_vlc(drive_path)
                    
        except wmi.x_wmi_timed_out:
            # Check if disc was removed
            if vlc_process and vlc_process.poll() is None:
                # If no CD drives have media, the disc was likely ejected
                ready_drives = [d for d in c.Win32_LogicalDisk(DriveType=4) if d.Size is not None]
                if not ready_drives:
                    print("Disc ejected. Stopping playback...")
                    vlc_process.terminate()
                    vlc_process = None
        except Exception as e:
            time.sleep(1)

if __name__ == "__main__":
    monitor_drive()