# -*- coding: utf-8 -*-
"""Ensure only one Claude Proxy Control window; restore if already running."""
from __future__ import annotations

import ctypes
import sys

MUTEX_NAME = "Local\\ClaudeProxyControl_Product_SingleInstance"
WINDOW_TITLES = (
    "Claude Proxy Control",
    "Claude Proxy Control — активация",
    "Claude Proxy Control - активация",
)

ERROR_ALREADY_EXISTS = 183
SW_RESTORE = 9
SW_SHOW = 5


def _bring_to_front() -> bool:
    user32 = ctypes.windll.user32
    for title in WINDOW_TITLES:
        hwnd = user32.FindWindowW(None, title)
        if not hwnd:
            continue
        if user32.IsIconic(hwnd):
            user32.ShowWindow(hwnd, SW_RESTORE)
        else:
            user32.ShowWindow(hwnd, SW_SHOW)
        user32.SetForegroundWindow(hwnd)
        return True
    return False


def acquire_or_focus_existing() -> ctypes.c_void_p | None:
    """
    Acquire app mutex. If another instance holds it, focus that window and return None.
    Caller must keep the returned handle alive for the process lifetime.
    """
    if sys.platform != "win32":
        return ctypes.c_void_p(1)

    kernel32 = ctypes.windll.kernel32
    handle = kernel32.CreateMutexW(None, False, MUTEX_NAME)
    if not handle:
        return ctypes.c_void_p(1)
    if kernel32.GetLastError() == ERROR_ALREADY_EXISTS:
        _bring_to_front()
        # small retry — window may still be creating
        if not _bring_to_front():
            import time

            time.sleep(0.4)
            _bring_to_front()
        return None
    return handle
