"""Small, conservative helpers for minimizing and restoring the Nelloz app window."""

from __future__ import annotations

from dataclasses import dataclass
import sys


@dataclass(frozen=True, slots=True)
class NellozWindowState:
    """The exact app window and whether it was already minimized."""

    handle: int
    was_minimized: bool


def _find_nelloz_window() -> tuple[int, bool] | None:
    if sys.platform != "win32":
        return None
    try:
        import ctypes
        from ctypes import wintypes

        user32 = ctypes.windll.user32
        candidates: list[tuple[int, int, bool]] = []
        foreground = int(user32.GetForegroundWindow())
        get_window_text = user32.GetWindowTextW
        get_window_text_length = user32.GetWindowTextLengthW
        get_window_text.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]
        get_window_text.restype = ctypes.c_int

        @ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
        def visit(hwnd: int, _lparam: int) -> bool:
            if not user32.IsWindowVisible(hwnd):
                return True
            length = int(get_window_text_length(hwnd))
            if length <= 0:
                return True
            title = ctypes.create_unicode_buffer(min(length + 1, 512))
            get_window_text(hwnd, title, len(title))
            normalized = title.value.strip().casefold()
            if not normalized or "nelloz" not in normalized:
                return True
            # Prefer the exact Edge app title, then ordinary Nelloz-prefixed
            # titles. This avoids touching unrelated windows when present.
            score = -1 if int(hwnd) == foreground else (0 if normalized == "nelloz" else 1)
            candidates.append((score, int(hwnd), bool(user32.IsIconic(hwnd))))
            return True

        if not user32.EnumWindows(visit, 0):
            return None
        if not candidates:
            return None
        score, handle, was_minimized = sorted(candidates, key=lambda item: (item[0], item[1]))[0]
        del score
        return handle, was_minimized
    except Exception:
        # The visual companion remains useful when the host window cannot be
        # discovered in a restricted desktop session.
        return None


def minimize_nelloz_window() -> NellozWindowState | None:
    """Minimize the visible Nelloz app and remember its prior state."""

    found = _find_nelloz_window()
    if found is None:
        return None
    handle, was_minimized = found
    if not was_minimized:
        try:
            import ctypes

            ctypes.windll.user32.ShowWindow(handle, 6)  # SW_MINIMIZE
        except Exception:
            return None
    return NellozWindowState(handle=handle, was_minimized=was_minimized)


def restore_nelloz_window(state: NellozWindowState | None) -> bool:
    """Restore only a window that this module minimized, without stealing focus."""

    if state is None or state.was_minimized or sys.platform != "win32":
        return False
    try:
        import ctypes

        user32 = ctypes.windll.user32
        if not user32.IsWindow(state.handle):
            return False
        user32.ShowWindow(state.handle, 9)  # SW_RESTORE
        return True
    except Exception:
        return False
