"""Window management — cross-platform."""

import platform
import subprocess


def window_list():
    """List open windows. Platform-specific."""
    system = platform.system().lower()
    try:
        if system == "linux":
            result = subprocess.run(
                ["wmctrl", "-l"], capture_output=True, text=True, timeout=5
            )
            if result.returncode == 0:
                windows = []
                for line in result.stdout.strip().split("\n"):
                    if not line.strip():
                        continue
                    parts = line.split(None, 3)
                    if len(parts) >= 4:
                        windows.append({"id": parts[0], "desktop": parts[1], "title": parts[3]})
                return {"success": True, "windows": windows}
            # Fallback: xdotool
            result = subprocess.run(
                ["xdotool", "search", "--onlyvisible", "--name", ""],
                capture_output=True, text=True, timeout=5,
            )
            return {"success": True, "windows": [{"id": wid.strip()} for wid in result.stdout.strip().split("\n") if wid.strip()]}

        elif system == "darwin":
            script = '''tell application "System Events" to get name of every process whose visible is true'''
            result = subprocess.run(
                ["osascript", "-e", script], capture_output=True, text=True, timeout=5
            )
            apps = [a.strip() for a in result.stdout.strip().split(",") if a.strip()]
            return {"success": True, "windows": [{"title": a} for a in apps]}

        elif system == "windows":
            # Use PowerShell
            ps_cmd = 'Get-Process | Where-Object {$_.MainWindowTitle -ne ""} | Select-Object MainWindowTitle | Format-Table -HideTableHeaders'
            result = subprocess.run(
                ["powershell", "-Command", ps_cmd],
                capture_output=True, text=True, timeout=5,
            )
            titles = [t.strip() for t in result.stdout.strip().split("\n") if t.strip()]
            return {"success": True, "windows": [{"title": t} for t in titles]}

        return {"success": False, "error": f"Unsupported platform: {system}"}
    except FileNotFoundError as e:
        return {"success": False, "error": f"Required tool not found: {e}. On Linux, install wmctrl or xdotool."}
    except Exception as e:
        return {"success": False, "error": str(e)}


def window_focus(title):
    """Focus a window by title. Platform-specific."""
    system = platform.system().lower()
    try:
        if system == "linux":
            subprocess.run(["wmctrl", "-a", title], timeout=5)
            return {"success": True, "focused": title}
        elif system == "darwin":
            script = f'tell application "{title}" to activate'
            subprocess.run(["osascript", "-e", script], timeout=5)
            return {"success": True, "focused": title}
        elif system == "windows":
            ps_cmd = f'''
            $w = Get-Process | Where-Object {{$_.MainWindowTitle -like "*{title}*"}} | Select-Object -First 1
            if ($w) {{ [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic"); [Microsoft.VisualBasic.Interaction]::AppActivate($w.Id) }}
            '''
            subprocess.run(["powershell", "-Command", ps_cmd], timeout=5)
            return {"success": True, "focused": title}
        return {"success": False, "error": f"Unsupported platform: {system}"}
    except Exception as e:
        return {"success": False, "error": str(e)}


def window_resize(title, x=None, y=None, width=None, height=None):
    """Resize/move a window. Linux only with wmctrl for now."""
    system = platform.system().lower()
    try:
        if system == "linux":
            gravity = "0"
            pos = f"{x or -1},{y or -1},{width or -1},{height or -1}"
            subprocess.run(["wmctrl", "-r", title, "-e", f"{gravity},{pos}"], timeout=5)
            return {"success": True, "resized": title}
        return {"success": False, "error": f"window_resize not yet supported on {system}"}
    except Exception as e:
        return {"success": False, "error": str(e)}
