import os
import sys
import time
import subprocess
import traceback

def main():
    os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
    os.environ["OPTIMUS_SKIP_MUTEX_FOR_DEBUG_TCL_BOOT"] = "1"
    cmd = [sys.executable, "-B", "-u", "run_live_desktop_with_copy_and_mic.py", "--open-ui"]
    
    print("Starting process...")
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    
    # Read output in a background thread
    def reader():
        for line in proc.stdout:
            print("[APP]", line, end="")
    
    import threading
    t = threading.Thread(target=reader, daemon=True)
    t.start()
    
    print("Waiting 6 seconds...")
    time.sleep(6)
    
    print("Attempting to close window gracefully...")
    try:
        import win32gui
        import win32con
        def enum_cb(hwnd, results):
            title = win32gui.GetWindowText(hwnd)
            if "Digital Optimus" in title or "Chat" in title or "tk" == title.lower() or "tk" in title.lower():
                win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
                print(f"Sent WM_CLOSE to window: {title} (hwnd {hwnd})")
        win32gui.EnumWindows(enum_cb, None)
    except Exception as e:
        print("win32gui error:", e)
        traceback.print_exc()

    print("Waiting for process to exit...")
    try:
        proc.wait(timeout=10)
        print(f"Process exited cleanly with code {proc.returncode}")
    except subprocess.TimeoutExpired:
        print("Process did not exit! Force killing...")
        proc.kill()
        print("Process killed.")

    print("\n--- RUNNING AGAIN TO REPRODUCE RELAUNCH ISSUE ---\n")
    proc2 = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    def reader2():
        for line in proc2.stdout:
            print("[APP2]", line, end="")
    t2 = threading.Thread(target=reader2, daemon=True)
    t2.start()
    
    print("Waiting 6 seconds on second run...")
    time.sleep(6)
    
    print("Attempting to close window gracefully (run 2)...")
    try:
        win32gui.EnumWindows(enum_cb, None)
    except Exception as e:
        pass
        
    try:
        proc2.wait(timeout=10)
        print(f"Run 2 Process exited cleanly with code {proc2.returncode}")
    except subprocess.TimeoutExpired:
        print("Run 2 Process did not exit! Force killing...")
        proc2.kill()

if __name__ == "__main__":
    main()
