import os

SAVE_LOCATION = "/mnt/homelab/games/ROMS/psx/m3u"
ROOT_DIRECTORY = "/mnt/homelab/games/ROMS/psx/img"


def remove_old_m3us():
    os.makedirs(SAVE_LOCATION, exist_ok=True)

    for file in os.listdir(SAVE_LOCATION):
        if file.endswith(".m3u"):
            os.remove(os.path.join(SAVE_LOCATION, file))


def create_m3us():
    for subdir, _, files in os.walk(ROOT_DIRECTORY):
        if subdir == ROOT_DIRECTORY:
            continue

        cue_files = sorted(f for f in files if f.lower().endswith(".cue"))

        if not cue_files:
            continue

        game = os.path.basename(subdir)
        m3u_path = os.path.join(SAVE_LOCATION, f"{game}.m3u")

        with open(m3u_path, "w", newline="\n") as m3u:
            for cue in cue_files:
                m3u.write(os.path.join(subdir, cue) + "\n")


remove_old_m3us()
create_m3us()
