"""
Process lifecycle management utilities.

This module provides functions for process termination, primarily used
as a fallback for critical errors where exception handling is not possible.

Note:
    The preferred way to handle errors is through exceptions defined in
    the exceptions module. hard_exit() should only be used as a last resort
    for unrecoverable situations where the process state is corrupted and
    normal exception handling cannot proceed.
"""

import ctypes
from typing import NoReturn

from ._internal.logging import debug_log, debug_traceback

_MODULE = "lifecycle"


def hard_exit(code: int = 1) -> NoReturn:
    """
    Forcefully terminate the process with the given exit code.

    This function uses the Windows API ExitProcess to immediately end
    the calling process and all its threads. No cleanup handlers,
    finally blocks, or atexit functions will be executed.

    Warning:
        This function should only be used as a last resort for unrecoverable
        errors where the process state is corrupted. For normal error handling,
        prefer raising exceptions (XBotFormError, WebViewError, etc.).

        Scenarios where hard_exit might be appropriate:
        - COM callback failure where returning normally would crash
        - Corrupted state where continuing would cause data loss
        - Deadlock situations that cannot be resolved

    Args:
        code: The exit code to return to the OS. Defaults to 1 (error).
              Use 0 for success, non-zero for errors.

    Returns:
        This function never returns (NoReturn).
    """
    debug_log(f"hard_exit({code})", _MODULE)
    debug_traceback(limit=8)
    ctypes.windll.kernel32.ExitProcess(code)
