#!/usr/bin/env python3
"""
Minimize All Windows - Python Version
Requires: pip3 install pyobjc-framework-Cocoa pyobjc-framework-Quartz

This uses native macOS APIs which should be more reliable than AppleScript.
"""

import time
from Cocoa import NSWorkspace, NSRunningApplication
from Quartz import (
    CGWindowListCopyWindowInfo,
    kCGWindowListOptionOnScreenOnly,
    kCGNullWindowID
)
import subprocess

def get_all_windows():
    """Get all visible windows from all apps"""
    window_list = CGWindowListCopyWindowInfo(
        kCGWindowListOptionOnScreenOnly,
        kCGNullWindowID
    )
    return window_list

def minimize_window_via_applescript(app_name):
    """Use AppleScript to minimize the frontmost window of an app"""
    script = f'''
    tell application "{app_name}"
        activate
    end tell
    delay 0.8
    tell application "System Events"
        tell process "{app_name}"
            set frontmost to true
            delay 0.4
            keystroke "m" using command down
        end tell
    end tell
    '''
    try:
        subprocess.run(['osascript', '-e', script], timeout=5, check=False)
        return True
    except Exception as e:
        print(f"Failed to minimize {app_name}: {e}")
        return False

def main():
    # Apps to skip
    skip_apps = {'Finder', 'SystemUIServer', 'Dock', 'Electron', 'MSTeams', 'nxdock'}
    skip_keywords = ['Helper', 'Agent']
    
    # Get all running applications
    workspace = NSWorkspace.sharedWorkspace()
    running_apps = workspace.runningApplications()
    
    processed_apps = set()
    
    for app in running_apps:
        app_name = app.localizedName()
        
        # Skip if already processed
        if app_name in processed_apps:
            continue
            
        # Skip system apps and problematic apps
        if app_name in skip_apps:
            continue
            
        # Skip apps with certain keywords
        if any(keyword in app_name for keyword in skip_keywords):
            continue
            
        # Skip if not a regular app
        if not app.activationPolicy() == 0:  # NSApplicationActivationPolicyRegular
            continue
            
        print(f"Processing: {app_name}")
        minimize_window_via_applescript(app_name)
        processed_apps.add(app_name)
        time.sleep(0.3)
    
    # Handle Finder windows separately
    print("Processing: Finder windows")
    finder_script = '''
    tell application "Finder"
        try
            set allWindows to every Finder window
            repeat with aWindow in allWindows
                set miniaturized of aWindow to true
            end repeat
        end try
    end tell
    '''
    subprocess.run(['osascript', '-e', finder_script], check=False)
    
    print("Done minimizing all windows")

if __name__ == '__main__':
    main()