# src/pytools/pydantic-settings/utils/internal.py
from typing import Any

from pydantic import BaseModel
from rich.text import Text
from rich.tree import Tree

def _type_name(annotation: Any) -> str:
    """
    Resolve a human-friendly type name for annotations that may not have __name__.
    """
    return annotation.__name__ if hasattr(annotation, "__name__") else str(annotation)


def _add_model_to_tree(tree: Tree, model: BaseModel) -> None:
    """
    Recursively add BaseModel fields to a rich Tree for structured display.
    """
    for field, field_info in model.__class__.model_fields.items():
        value = getattr(model, field)
        typename = _type_name(field_info.annotation)

        label = Text.assemble(
            (field, "grey70"),
            (f" ({typename})", "grey50"),
        )

        if isinstance(value, BaseModel):
            branch = tree.add(label)
            _add_model_to_tree(branch, value)
        else:
            leaf = Text.assemble(
                label,
                (": ", "grey70"),
                (repr(value), "grey70"),
            )
            tree.add(leaf)