import os

from datetime import datetime

def generateSoundMap(soundPath:str):
    soundMap = {}

    # Get the list of categories (subdirectories) in the Sound directory
    categories = os.listdir(soundPath)
    for c in categories:
        # for each voice in the category, get the list of files
        voices = os.listdir(os.path.join(soundPath, c))
        # put the voices into the category
        # also output the category and voices as a dictionary
        soundMap[c] = voices

    # the result sound map is like {category1: [sound1, sound2, ...], ...}
    return soundMap

def processSoundMap(soundMap:dict, suffix:str):
    soundOutput = []
    soundList = []
    for category in soundMap: # for each category
        # append the COMMENTS HEADER
        soundOutput.append(f"--{category}: {str(len(soundMap[category]))}\n")
        soundList.append(f"--{category}: {str(len(soundMap[category]))}\n")

        # process each sounds
        for voice in soundMap[category]:
            name = voice.split(".")[0] # remove file extension
            
            # assign color based on category
            if category == "warning":
                color = "ffff7c0a" # Druid
            elif category == "individual":
                color = "ffc41e3a" # Death Knight
            elif category == "kicks": 
                color = "ff0070dd" # Shaman
            elif category == "special":
                color = "ff8788ee" # Warlock
            elif category == "team":
                color = "fff48cba" # Paladin
            elif category == "tank":
                color = "ffC69B6D" # Warrior
            elif category == "incoming":
                color = "ffFFF468" # Rogue
            else: # default
                color = "ffffffff" # Priest

            # add the voice to the output list with the appropriate color and name into the output list
            inputStr = f"LSM:Register(\"sound\", \"|c{color}{name}-{suffix}|r\", [[Interface\\Addons\\SharedMedia_HBLyx\\{suffix}_Sound\\{category}\\{name}.ogg]])\n"
            soundOutput.append(inputStr)
            soundList.append(f"{name}-{suffix}\n")
    
    return soundOutput, soundList

def processSounds(rootPath:str, soundFolderName:str):
    # process the sound path and sound suffix
    suffix = soundFolderName.split("_")[0]
    
    # get voice categories from the author path
    soundMap = generateSoundMap(os.path.join(rootPath, soundFolderName))

    # get the list of voices in each category with respective colors
    soundOutput, soundList = processSoundMap(soundMap=soundMap, suffix=suffix)

    return soundOutput, soundList

def processFolder(rootPath:str, folderName:str, type:str):
    output = []
    outputList = []

    if type == "texture":
        type = "statusbar"

    files = os.listdir(os.path.join(rootPath, folderName))
    for f in files:
        name = f.split(".")[0]
        string = f"LSM:Register(\"{type}\", \"{name}\", [[Interface\\Addons\\SharedMedia_HBLyx\\{folderName}\\{f}]])\n"
        output.append(string)
        outputList.append(f"{name}\n")

    return output, outputList

def writeFiles(outputs:dict, outputsLists:dict, SharedMediaLuaName:str, date:str=""):
    with open(SharedMediaLuaName + "_" + date + ".lua", "w", encoding="utf-8") as file:
        file.writelines("local LSM = LibStub(\"LibSharedMedia-3.0\")\n")
        file.writelines("\n")
        for type in outputs:
            if type == "sound":
                file.writelines(f"--{type.upper()}\n")
            else:
                file.writelines(f"--{type.upper()}: {str(len(outputsLists[type]))}\n")
                
            for out in outputs[type]:
                file.writelines(out)
            file.writelines("\n")

    with open("MediaList_" + date + ".txt", "w", encoding="utf-8") as file:
        for type in outputsLists:
            if type == "sound":
                file.writelines(f"--{type.upper()}\n")
            else:
                file.writelines(f"--{type.upper()}: {str(len(outputsLists[type]))}\n")

            for out in outputsLists[type]:
                file.writelines(out)
            file.writelines("\n")


if __name__ == "__main__":
    # specify the path to the SharedMedia_HBLyx directory (OS Path)
    outputPath = os.getcwd() # if this script is in the SharedMedia directory, the current working directory is just the output Path

    # get the current date and format it as MMDDYY for the output file name
    today = datetime.today()
    date =  str(today.month).zfill(2) + "_" + str(today.day).zfill(2) + "_" + str(today.year)[2:] # format the date as MM_DD_YY

    backgroundOutput, backgroundList = processFolder(rootPath=outputPath, folderName="backgrounds", type="background")
    borderOutput, borderList = processFolder(rootPath=outputPath, folderName="borders", type="border")
    fontOutput, fontList = processFolder(rootPath=outputPath, folderName="fonts", type="font")
    textureOutput, textureList = processFolder(rootPath=outputPath, folderName="textures", type="texture")

    # specify the existing authors to process and process them below
    # sound is special, and all sounds folder are like "xxx_Sound"
    soundOutput, soundList = processSounds(rootPath=outputPath, soundFolderName="AI-generated_Sound")

    # after we have all output and outputList
    outputs = {}
    outputs["sound"], outputs["background"], outputs["border"], outputs["font"], outputs["texture"] = soundOutput, backgroundOutput, borderOutput, fontOutput, textureOutput
    outputsLists= {}
    outputsLists["sound"], outputsLists["background"], outputsLists["border"], outputsLists["font"], outputsLists["texture"] = soundList, backgroundList, borderList, fontList, textureList

    writeFiles(outputs=outputs, outputsLists=outputsLists, SharedMediaLuaName="SharedMedia_HBLyx", date=date)

