import os
import zipfile
import subprocess
import time

def install_novindesk(base_drive: str = r"D:\\") -> str:
    """
    Extract and automatically install NovinDesk by navigating the installer UI.
    """
    base_dir = os.path.join(base_drive, "NovinPardazOne")
    soft_dir = os.path.join(base_dir, "NovinSoft")

    zip_filename = "NovinDesk.zip"
    source_zip_path = os.path.join(soft_dir, zip_filename)
    extract_target_dir = os.path.join(soft_dir, "NovinDesk")

    if not os.path.exists(source_zip_path):
        raise FileNotFoundError(f"[-] File {zip_filename} was not found in {soft_dir}!")

    os.makedirs(extract_target_dir, exist_ok=True)

    print(f"[+] Extracting {zip_filename} ...")
    with zipfile.ZipFile(source_zip_path, 'r') as zip_ref:
        zip_ref.extractall(extract_target_dir)
    print("  [+] Extraction completed successfully.")

    exe_file = None
    for root, dirs, files in os.walk(extract_target_dir):
        for file in files:
            if file.lower().endswith(".exe"):
                exe_file = os.path.join(root, file)
                break

    if not exe_file:
        raise FileNotFoundError("[-] No executable file (.exe) found!")

    print(f"[+] Launching installer {os.path.basename(exe_file)} ...")
    
    # Launch application for installation
    subprocess.Popen([exe_file, "--install"])
    
    # Wait 5 seconds for the window to fully load
    time.sleep(5)

    try:
        import pyautogui
        
        # 1. Close any secondary/side dialogs
        pyautogui.press('escape')
        time.sleep(0.5)

        # 2. Press Tab 4 times to navigate directly to the 'Accept & Install' button
        for _ in range(4):
            pyautogui.press('tab')
            time.sleep(0.2)
        
        # 3. Press Enter on the install button
        pyautogui.press('enter')
        print("  [+] Confirmation sent and automated installation started.")
    except Exception as err:
        print(f"  [-] Automation error: {err}")

    return exe_file

if __name__ == "__main__":
    os.system("chcp 65001 > nul")
    print("[+] Running NovinDesk installation module ...")
    try:
        install_novindesk(base_drive=r"D:\\")
    except Exception as e:
        print(f"[-] Error: {e}")
