import os
import sys
import subprocess
import urllib.request
from win32com.client import Dispatch

def download_iw4x_launcher(save_path):
    if os.path.exists(save_path):
        print("iw4x launcher already exists, skipping download.")
        return
    url = "https://github.com/iw4x/launcher/releases/latest/download/iw4x-launcher.exe"
    print(f"Downloading iw4x launcher to {save_path}...")
    urllib.request.urlretrieve(url, save_path)
    print("Download complete.")

def run_launcher_with_args(launcher_path, install_dir, mode):
    # Remove trailing slash if present
    install_dir = install_dir.rstrip("\\/")
    print(f"Launching iw4x launcher in {mode} mode...")
    subprocess.run([
        launcher_path,
        mode,
        "--bonus",
        "-u",
        "--path", install_dir
    ], check=True)

def create_shortcut(launcher_path, mode, shortcut_name):
    start_menu_dir = os.path.join(os.environ["APPDATA"], "Microsoft", "Windows", "Start Menu", "Programs", "Steam")
    os.makedirs(start_menu_dir, exist_ok=True)
    shortcut_path = os.path.join(start_menu_dir, f"{shortcut_name}.lnk")

    print(f"Creating shortcut: {shortcut_path}")
    shell = Dispatch("WScript.Shell")
    shortcut = shell.CreateShortcut(shortcut_path)
    shortcut.TargetPath = launcher_path
    shortcut.WorkingDirectory = os.path.dirname(launcher_path)
    shortcut.IconLocation = launcher_path
    shortcut.Save()

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python update_iw4x.py <install_path>")
        sys.exit(1)

    install_dir = sys.argv[1]
    if not os.path.isdir(install_dir):
        print("Invalid install directory:", install_dir)
        sys.exit(1)

    launcher_path = os.path.join(install_dir, "iw4x-launcher.exe")
    download_iw4x_launcher(launcher_path)

    # Run updater once with iw4x mode
    run_launcher_with_args(launcher_path, install_dir, "iw4x")

    # Create launch shortcut
    create_shortcut(launcher_path, "iw4x", "Call of Duty Modern Warfare 2 (iw4x)")
