"""
Windows message loop implementation.

This module provides the standard Windows message loop
using GetMessage, TranslateMessage, and DispatchMessage.
"""

import win32gui

from ._internal.logging import debug_log

_MODULE = "message_loop"


def run_message_loop() -> None:
    """
    Run the standard Windows message loop.

    This function blocks until a WM_QUIT message is received (via PostQuitMessage).
    It uses the standard Win32 message pump without sleep, polling, or threading.

    The message loop dispatches messages to window procedures, which may raise
    exceptions. These exceptions propagate through the message dispatch chain
    and can terminate the loop.

    Note:
        This function may exit in three ways:
        1. WM_QUIT message received (normal exit)
        2. GetMessage returns an error
        3. An exception is raised during message dispatch (e.g., _InternalCancelSignal)

    Raises:
        _InternalCancelSignal: If the user cancels the form (raised by window procedure).
        _InternalExitSignal: If a critical error occurs (raised by WebView handlers).
    """
    while True:
        try:
            ret, msg = win32gui.GetMessage(0, 0, 0)
        except Exception as exc:
            debug_log(f"GetMessage exception: {exc!r}", _MODULE)
            break

        if ret == 0:  # WM_QUIT
            debug_log("Message loop received WM_QUIT", _MODULE)
            break

        if ret == -1:  # Error
            debug_log("Message loop received error from GetMessage", _MODULE)
            break

        win32gui.TranslateMessage(msg)
        win32gui.DispatchMessage(msg)
