import os
import ctypes
import sys
import subprocess
import urllib.request
from win32com.client import Dispatch
import hashlib
import tempfile

def sha256_checksum(filename, block_size=65536):
    sha256 = hashlib.sha256()
    with open(filename, 'rb') as f:
        for block in iter(lambda: f.read(block_size), b''):
            sha256.update(block)
    return sha256.hexdigest()

def download_file_with_user_agent(url, save_path):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/114.0.0.0 Safari/537.36'
    }
    req = urllib.request.Request(url, headers=headers)
    with urllib.request.urlopen(req) as response, open(save_path, 'wb') as out_file:
        out_file.write(response.read())

def download_TotemArts_launcher(save_path):
    url = "https://launcher.totemarts.services/Totem-Arts-Launcher-latest.exe"

    # Check if file exists and compare hashes for update
    if os.path.exists(save_path):
        print("TotemArts launcher exists, checking for update...")
        # Download to temp file with User-Agent header
        with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
            tmp_path = tmp_file.name
        download_file_with_user_agent(url, tmp_path)

        old_hash = sha256_checksum(save_path)
        new_hash = sha256_checksum(tmp_path)

        if old_hash == new_hash:
            print("Launcher is up-to-date, skipping download.")
            os.remove(tmp_path)
            return False  # No update
        else:
            print("New launcher version found, updating...")
            os.replace(tmp_path, save_path)
            return True  # Updated
    else:
        print(f"Downloading TotemArts launcher to {save_path}...")
        download_file_with_user_agent(url, save_path)
        print("Download complete.")
        return True  # New download

def run_silent_installer(launcher_path, install_dir):
    install_dir = install_dir.rstrip("\\/")
    print(f"Running silent installer to install to: {install_dir}")

    # Use ShellExecuteEx with 'runas' verb to request elevation
    params = f'/S /D={install_dir}'

    # ShellExecute returns an instance handle, >32 means success
    ret = ctypes.windll.shell32.ShellExecuteW(None, "runas", launcher_path, params, None, 1)
    if ret <= 32:
        print(f"Failed to launch installer with elevation, error code: {ret}")
        sys.exit(1)

def create_shortcut(target_exe, 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 = target_exe
    shortcut.WorkingDirectory = os.path.dirname(target_exe)
    shortcut.IconLocation = target_exe
    shortcut.Save()

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python update_totemarts.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, "TotemArts-launcher.exe")
    updated = download_TotemArts_launcher(launcher_path)

    if updated:
        run_silent_installer(launcher_path, install_dir)
    else:
        print("Skipping installer run since launcher is up-to-date.")

    renegade_exe = os.path.join(install_dir, "RenegadeX.exe")
    if not os.path.isfile(renegade_exe):
        print(f"Warning: Could not find expected executable at {renegade_exe} to create shortcut.")
        create_shortcut(launcher_path, "Renegade X (TotemArts Launcher)")
    else:
        create_shortcut(renegade_exe, "Renegade X")

    print("Done.")
