import os
import time
import pyautogui
import win32gui
import win32con

# ---------------------------------------------------------
# CONFIG: Output folder
# ---------------------------------------------------------
OUTPUT_DIR = r"C:\Temp\projectWindows\JPG"
os.makedirs(OUTPUT_DIR, exist_ok=True)

# ---------------------------------------------------------
# Collect all windows visible in Alt+Tab
# ---------------------------------------------------------
def is_alt_tab_window(hwnd):
    # Must be visible
    if not win32gui.IsWindowVisible(hwnd):
        return False

    # Must have a title
    title = win32gui.GetWindowText(hwnd)
    if not title:
        return False

    # Must not be tool windows
    if win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) & win32con.WS_EX_TOOLWINDOW:
        return False

    # Must not be child windows
    if win32gui.GetParent(hwnd) != 0:
        return False

    return True

windows = []
def enum_handler(hwnd, _):
    if is_alt_tab_window(hwnd):
        windows.append(hwnd)

win32gui.EnumWindows(enum_handler, None)

print(f"Detected {len(windows)} Alt+Tab windows")

# ---------------------------------------------------------
# Screenshot each window
# ---------------------------------------------------------
for i, hwnd in enumerate(windows, start=1):
    try:
        # Bring window to foreground
        win32gui.SetForegroundWindow(hwnd)
        time.sleep(1.2)  # allow redraw

        # Screenshot entire screen
        screenshot_path = os.path.join(OUTPUT_DIR, f"window_{i}.jpg")
        img = pyautogui.screenshot()
        img.save(screenshot_path)

        print(f"Saved: {screenshot_path}")

    except Exception as e:
        print(f"Failed on window {i}: {e}")

print("All screenshots complete.")
