"""
Unified logging utilities for xbot-form.

This module provides a single debug logging implementation used throughout the SDK.
Debug logging can be enabled by setting the WEBVIEW_FORM_DEBUG environment variable to "1".
"""

import os
import traceback as tb_module
from typing import Optional

_DEBUG_ENV = "WEBVIEW_FORM_DEBUG"
_debug_enabled: Optional[bool] = None


def is_debug_enabled() -> bool:
    """Check if debug mode is enabled via environment variable."""
    global _debug_enabled
    if _debug_enabled is None:
        _debug_enabled = os.environ.get(_DEBUG_ENV) == "1"
    return _debug_enabled


def set_debug_enabled(enabled: bool) -> None:
    """
    Programmatically enable or disable debug mode.

    Args:
        enabled: True to enable debug logging, False to disable.
    """
    global _debug_enabled
    _debug_enabled = enabled


def debug_log(message: str, module: str = "") -> None:
    """
    Log a debug message if debug mode is enabled.

    Args:
        message: The message to log.
        module: Optional module name prefix for the message.
    """
    if is_debug_enabled():
        prefix = f"[{module}] " if module else ""
        print(f"{prefix}{message}", flush=True)


def debug_traceback(limit: int = 8) -> None:
    """
    Print a traceback if debug mode is enabled.

    This is useful for debugging to see the call stack that led to
    a particular point in the code.

    Args:
        limit: Maximum number of stack frames to print.
    """
    if is_debug_enabled():
        print("".join(tb_module.format_stack(limit=limit)), flush=True)
