"""Desktop-Ordner finden – Jam versteckt sich dahinter."""

from __future__ import annotations

import ctypes
import random
from ctypes import wintypes

user32 = ctypes.windll.user32


class RECT(ctypes.Structure):
    _fields_ = [
        ("left", wintypes.LONG),
        ("top", wintypes.LONG),
        ("right", wintypes.LONG),
        ("bottom", wintypes.LONG),
    ]


def _enum_callback(hwnd: int, results: list[tuple[int, str, RECT]]) -> bool:
    if not user32.IsWindowVisible(hwnd):
        return True
    length = user32.GetWindowTextLengthW(hwnd) + 1
    buf = ctypes.create_unicode_buffer(length)
    user32.GetWindowTextW(hwnd, buf, length)
    title = buf.value or ""
    rect = RECT()
    user32.GetWindowRect(hwnd, ctypes.byref(rect))
    w = rect.right - rect.left
    h = rect.bottom - rect.top
    if 40 < w < 400 and 30 < h < 400 and title:
        results.append((hwnd, title, rect))
    return True


def find_folder_windows() -> list[tuple[int, str, RECT]]:
    results: list[tuple[int, str, RECT]] = []
    cb = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)(
        lambda h, _: _enum_callback(h, results)
    )
    user32.EnumWindows(cb, 0)
    folders = [
        (h, t, r)
        for h, t, r in results
        if any(x in t.lower() for x in ("ordner", "folder", "desktop", "explorer"))
        or (r.right - r.left) < 200
    ]
    return folders[:20] if folders else results[:8]


def hide_behind_folder() -> tuple[int, int] | None:
    """Position hinter einem kleinen Fenster/Ordner."""
    wins = find_folder_windows()
    if not wins:
        return None
    _, _title, rect = random.choice(wins)
    x = rect.left + 8
    y = rect.top + max(0, (rect.bottom - rect.top) // 2 - 30)
    return x, y
