from logging import Logger
from typing import Any, Optional, Union

from rich.console import Console, ConsoleRenderable
from rich.text import Text

from pytools.logging.utils import resolve_log_level

from .pprint_obj import pprint_obj


def pprint(
    message: Union[str, ConsoleRenderable, Any],
    style: Optional[str] = None,
    *,
    debug: bool = False,
    console: Optional[Console] = None,
    logger: Optional[Logger] = None,
    log_level: str = "DEBUG",
    **kwargs: Any,
) -> None:
    """
    Print a message or object. If message is a string or ConsoleRenderable, prints it directly.
    Otherwise, delegates to pprint_obj for intelligent object printing.

    Args:
        message: String, ConsoleRenderable, or any object to print
        style: Optional style for string messages
        debug: Override debug flag
        console: Optional Rich console to use
        logger: Optional Logger to use
        log_level: Log level for logger
        **kwargs: Additional keyword arguments passed to pprint_obj if needed
    """
    if not debug:
        return

    # If it's a string or ConsoleRenderable, use the original logic
    if isinstance(message, (str, ConsoleRenderable)):
        # --- CASE 1: Rich console available ---
        if console:
            renderable = message
            if isinstance(message, str):
                renderable = Text(message, style=style)

            console.print(renderable)
            return

        # --- CASE 2: No console → extract plain text safely ---
        temp_console = Console(force_terminal=False, color_system=None, width=120)
        with temp_console.capture() as capture:
            temp_console.print(message)

        text = capture.get().rstrip()

        # --- CASE 3: Logger fallback ---
        if logger:
            log_level = resolve_log_level(log_level)
            logger.log(log_level, text)
        else:
            print(text)
    else:
        # Delegate to pprint_obj for any other type
        pprint_obj(
            message,
            debug=debug,
            console=console,
            logger=logger,
            log_level=log_level,
            **kwargs,
        )
