import os
import sys
import zipfile
import winreg

def get_steam_path():
    # 1. Tenta pegar pelo registro do Windows
    registry_paths = [
        (winreg.HKEY_CURRENT_USER, r"Software\Valve\Steam", "SteamPath"),
        (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Valve\Steam", "InstallPath"),
        (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Valve\Steam", "InstallPath")
    ]
    
    for hkey, subkey, val_name in registry_paths:
        try:
            with winreg.OpenKey(hkey, subkey) as key:
                val, _ = winreg.QueryValueEx(key, val_name)
                if val and os.path.exists(val):
                    return os.path.normpath(val)
        except Exception:
            pass
            
    # 2. Se o script estiver sendo rodado direto da pasta da Steam
    cwd = os.getcwd()
    if os.path.exists(os.path.join(cwd, "steam.exe")):
        return cwd
        
    # 3. Caminhos padrao
    default_paths = [
        r"C:\Program Files (x86)\Steam",
        r"C:\Program Files\Steam",
        r"D:\Steam",
        r"E:\Steam"
    ]
    for p in default_paths:
        if os.path.exists(p):
            return p
            
    return None

def create_luatools_package():
    steam_path = get_steam_path()
    if not steam_path or not os.path.exists(steam_path):
        print("[-] Pasta da Steam nao encontrada. Execute o script dentro da pasta da Steam ou certifique-se de que a Steam esta instalada.")
        return

    print(f"[+] Pasta da Steam identificada em: {steam_path}")
    
    # DLLs de injecao do LuaTools / OpenSteamTool (seleciona apenas 1)
    possible_dlls = ["dwmapi.dll", "version.dll"]
    chosen_dll = None
    
    for dll in possible_dlls:
        p = os.path.join(steam_path, dll)
        if os.path.exists(p):
            chosen_dll = dll
            break
            
    if not chosen_dll:
        ost_path = os.path.join(steam_path, "OpenSteamTool.dll")
        if os.path.exists(ost_path):
            chosen_dll = "dwmapi.dll"
            
    files_to_pack = []
    
    # 1. DLL principal de injecao
    if chosen_dll and os.path.exists(os.path.join(steam_path, chosen_dll)):
        files_to_pack.append((os.path.join(steam_path, chosen_dll), chosen_dll))
        
    # 2. OpenSteamTool.dll & opensteamtool.toml
    for item in ["OpenSteamTool.dll", "opensteamtool.toml"]:
        full_p = os.path.join(steam_path, item)
        if os.path.exists(full_p):
            files_to_pack.append((full_p, item))
            
    # 3. Pasta config/stplug-in
    stplugin_dir = os.path.join(steam_path, "config", "stplug-in")
    
    output_zip = os.path.join(os.getcwd(), "luatools_fix.zip")
    
    print("[+] Criando arquivo ZIP das dependencias do LuaTools...")
    with zipfile.ZipFile(output_zip, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for full_path, arcname in files_to_pack:
            zipf.write(full_path, arcname)
            print(f"  -> Adicionado arquivo: {arcname}")
            
        if os.path.exists(stplugin_dir):
            for root, _, files in os.walk(stplugin_dir):
                for file in files:
                    abs_f = os.path.join(root, file)
                    rel_path = os.path.relpath(abs_f, steam_path)
                    zipf.write(abs_f, rel_path)
                    print(f"  -> Adicionado plugin/manifesto: {rel_path}")

    print(f"\n[SUCESSO] Pacote criado com sucesso em: {output_zip}")
    print("Voce pode enviar esse arquivo 'luatools_fix.zip' para o seu servidor web ou GitHub!")

if __name__ == "__main__":
    create_luatools_package()
