import os

TARGET_DIR = "src/content/docs/szmgr"

def leading_space(text: str) -> str:
    """Returns only the leading space of a line"""
    return " " * (len(text) - len(text.lstrip()))

files = [f for f in os.listdir(TARGET_DIR) if f.endswith(".md")]

for f in files:
    print(f"\t- {f}")
    lines = []
    with open(os.path.join(TARGET_DIR, f), "r") as file:
        lines = file.readlines()
    
    dl_mode_active = False
    dl_indent = ""

    for i in range(len(lines) - 1):
        l = lines[i]
        l2 = lines[i+1]
        indent = leading_space(l)

        if "**⚠️ WARNING**\\" in l:
            lines[i] = indent + "> [!WARNING]\n"
            lines[i+1] = indent + "> " + l2.lstrip()
        elif "**💡 TIP**\\" in l:
            lines[i] = indent + "> [!TIP]\n"
            lines[i+1] = indent + "> " + l2.lstrip()
        elif "**📌 NOTE**\\" in l:
            lines[i] = indent + "> [!NOTE]\n"
            lines[i+1] = indent + "> " + l2.lstrip()
        elif "**❗ IMPORTANT**\\" in l:
            lines[i] = indent + "> [!IMPORTANT]\n"
            lines[i+1] = indent + "> " + l2.lstrip()
    
        if "<dl>" in l:
            dl_mode_active = True
            dl_indent = leading_space(l)
            if "IMPORTANT" in l:
                lines[i] = dl_indent + "> [!IMPORTANT]\n"
            elif "WARNING" in l:
                lines[i] = dl_indent + "> [!WARNING]\n"
            elif "NOTE" in l:
                lines[i] = dl_indent + "> [!NOTE]\n"
            elif "TIP" in l:
                lines[i] = dl_indent + "> [!TIP]\n"
            else:
                print("UNRECOGNIZED LINE")
                print(l)
            
            continue
        
        if dl_mode_active:
            if "</dl>" in l:
                lines[i] = dl_indent + "\n"
                dl_mode_active = False
                # Potential cleanup, don't leave <br> hanging
                if "> <br>" in lines[i - 1]:
                    lines[i - 1] = "" # Delete
            else:
                if l.lstrip():
                    lines[i] = dl_indent + "> " + l.lstrip()
                else:
                    if "> [!" in lines[i - 1]: 
                        # if previous line is the callout header, don't put a <br> here
                        lines[i] = ""
                    else:
                        lines[i] = dl_indent + "> <br>\n"


    with open(os.path.join(TARGET_DIR, f), "w") as file:
        file.writelines(lines)
