"""Windows foreground-window juggling for captcha focus isolation.

When uc_gui_click_captcha() clicks via pyautogui, the target browser must be
the foreground window for Chrome to process the click. We save the user's
current foreground HWND, bring the browser forward, do the click, then
restore the user's window so their typing / input doesn't get eaten.
"""
from contextlib import contextmanager
from typing import Optional

from utils.logger import child

log = child("focus")


def _win32():
    try:
        import win32gui
        import win32con
        import win32process
        return win32gui, win32con, win32process
    except Exception:
        return None, None, None


def get_foreground_hwnd() -> Optional[int]:
    win32gui, _, _ = _win32()
    if win32gui is None:
        return None
    try:
        return win32gui.GetForegroundWindow()
    except Exception:
        return None


def set_foreground(hwnd: int) -> bool:
    win32gui, win32con, _ = _win32()
    if win32gui is None or not hwnd:
        return False
    try:
        # ShowWindow first in case it's minimized
        try:
            win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
        except Exception:
            pass
        win32gui.SetForegroundWindow(hwnd)
        return True
    except Exception as e:
        log.debug(f"SetForegroundWindow failed: {e}")
        return False


def find_browser_hwnd_by_title(needle: str) -> Optional[int]:
    """Find the top-level HWND whose window title contains `needle`."""
    win32gui, _, _ = _win32()
    if win32gui is None:
        return None
    matches = []

    def _enum(hwnd, _):
        try:
            if not win32gui.IsWindowVisible(hwnd):
                return True
            title = win32gui.GetWindowText(hwnd)
            if title and needle.lower() in title.lower():
                matches.append(hwnd)
        except Exception:
            pass
        return True

    try:
        win32gui.EnumWindows(_enum, None)
    except Exception:
        pass
    return matches[0] if matches else None


def find_browser_hwnd_by_pid(pid: int) -> Optional[int]:
    """Find a top-level HWND belonging to the given process id."""
    win32gui, _, win32process = _win32()
    if win32gui is None:
        return None
    matches = []

    def _enum(hwnd, _):
        try:
            if not win32gui.IsWindowVisible(hwnd):
                return True
            _, wpid = win32process.GetWindowThreadProcessId(hwnd)
            if wpid == pid and win32gui.GetWindowText(hwnd):
                matches.append(hwnd)
        except Exception:
            pass
        return True

    try:
        win32gui.EnumWindows(_enum, None)
    except Exception:
        pass
    return matches[0] if matches else None


@contextmanager
def isolated_focus(browser_hwnd: Optional[int]):
    """Temporarily bring `browser_hwnd` forward; restore user's window on exit."""
    user_hwnd = get_foreground_hwnd()
    try:
        if browser_hwnd:
            set_foreground(browser_hwnd)
        yield
    finally:
        if user_hwnd and user_hwnd != browser_hwnd:
            try:
                set_foreground(user_hwnd)
            except Exception:
                pass


def find_browser_hwnd(driver) -> Optional[int]:
    """Best-effort: try to find Chrome window HWND owned by the driver."""
    # Chrome title is typically "<page title> - Google Chrome" or "- Brave"
    try:
        title = driver.title or ""
    except Exception:
        title = ""
    for needle in (title, "Google Chrome", "Chromium", "Brave"):
        if not needle:
            continue
        h = find_browser_hwnd_by_title(needle)
        if h:
            return h
    return None
