import os
import win32gui

_DEBUG_ENV = "WEBVIEW_FORM_DEBUG"


def _debug_log(message: str) -> None:
    if os.environ.get(_DEBUG_ENV) == "1":
        print(message, flush=True)


def run_message_loop() -> None:
    """
    Runs the standard Windows message loop using pywin32.

    This function blocks until a WM_QUIT message is received (via PostQuitMessage).
    It strictly uses GetMessage, TranslateMessage, and DispatchMessage as requested.
    No sleep, polling, or threading is used.
    """
    # GetMessage retrieves a message from the calling thread's message queue.
    # It blocks until a message is available.
    # Arguments: (hwnd, wMsgFilterMin, wMsgFilterMax)
    # hwnd=0 (None) means retrieve messages for any window belonging to the current thread,
    # and any messages on the current thread's message queue whose hwnd is NULL.
    while True:
        # returns (result, msg)
        # result is 0 if WM_QUIT, -1 if error, otherwise nonzero.
        try:
            ret, msg = win32gui.GetMessage(0, 0, 0)
        except Exception as exc:
            _debug_log(f"GetMessage exception: {exc!r}")
            break

        if ret == 0:  # WM_QUIT
            _debug_log("Message loop received WM_QUIT")
            break

        if ret == -1:  # Error
            _debug_log("Message loop received error from GetMessage")
            # In a strict loop, we should break on error to avoid infinite loops
            break

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