import os
import time
import subprocess
import ctypes
from ctypes import wintypes

user32 = ctypes.windll.user32
shell32 = ctypes.windll.shell32

def test_method(name, fn):
    print(f"\n=== Testing {name} ===")
    # Clean previous
    subprocess.run(['powershell', '-Command', 'Stop-Process -Name notepad -Force -ErrorAction SilentlyContinue'], capture_output=True)
    time.sleep(0.5)
    
    fn()
    time.sleep(1.5)
    
    # Check with powershell
    p = subprocess.run(['powershell', '-Command', 'Get-Process notepad -ErrorAction SilentlyContinue | Select-Object Id, ProcessName, MainWindowTitle, MainWindowHandle | ConvertTo-Json'], capture_output=True, text=True)
    print("Result:", p.stdout.strip())

# 1. os.startfile
test_method("os.startfile", lambda: os.startfile(r"C:\Windows\System32\notepad.exe"))

# 2. ctypes ShellExecuteW
test_method("ctypes ShellExecuteW", lambda: shell32.ShellExecuteW(None, "open", r"C:\Windows\System32\notepad.exe", None, None, 1))

# 3. subprocess.Popen without shell
test_method("subprocess.Popen raw", lambda: subprocess.Popen([r"C:\Windows\System32\notepad.exe"]))

# 4. subprocess.Popen with shell=True
test_method("subprocess.Popen shell=True", lambda: subprocess.Popen("notepad.exe", shell=True))

# 5. win32com Shell.Application
def run_win32com():
    import pythoncom, win32com.client
    pythoncom.CoInitialize()
    sh = win32com.client.Dispatch("Shell.Application")
    sh.ShellExecute(r"C:\Windows\System32\notepad.exe", "", "", "open", 1)
test_method("win32com Shell.Application", run_win32com)
