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

from pydantic import BaseModel
from rich.console import Console


def _get_object_title(model: BaseModel, ovverride: Optional[str] = None) -> str:
    return ovverride or model.__class__.__name__

def pprint_model(
    model: Union[BaseModel, dict, list, Any],
    title: Optional[str] = None,
    *,
    debug: bool = False,
    console: Optional[Console] = None,
    logger: Optional[Logger] = None,
    log_level: Optional[str] = "DEBUG",
    **kwargs: Any,
) -> None:
    """
    Print a Pydantic model, dict, or list of models respecting rich and debug settings.

    Args:
        model: Pydantic model, dict, or list of models/dicts
        debug: Override debug flag
        console: Optional Rich console to use; if None, one is created
        logger: Optional Logger to use
        log_level: Log level for logger
    """
    if not debug:
        return

    # Check if it's a BaseModel or list of BaseModels - handle specially
    if isinstance(model, BaseModel):
        object_title = _get_object_title(model, title)
        
        if console:
            from .print import pretty_model
            pretty_model(model, title=object_title, console=console, panel=kwargs.get('panel', False))
        else:
            if logger:
                logger.log(log_level, f"{object_title}:\n{model.model_dump_json(indent=2)}")
            else:
                print(f"{object_title}:")
                print(model.model_dump_json(indent=2))
        return
    
    if isinstance(model, list) and model and isinstance(model[0], BaseModel):
        object_title = _get_object_title(model[0], title)
        
        if console:
            from .print import pretty_model
            for i, item in enumerate(model):
                pretty_model(item, title=object_title, console=console, panel=kwargs.get('panel', False))
        else:
            if logger:
                for i, item in enumerate(model):
                    logger.log(log_level, f"Object {i+1}:\n{item.model_dump_json(indent=2)}")
            else:
                print(f"{object_title}:")
                for i, item in enumerate(model):
                    print(f"Object {i+1}:")
                    print(item.model_dump_json(indent=2))
        return

    # For all other cases, delegate to pprint_obj
    from pytools.debugging.pprint_obj import pprint_obj
    pprint_obj(model, debug=debug, console=console, logger=logger, log_level=log_level or "DEBUG", **kwargs)
