# src/pytools/pydantic-settings/utils/settings_to_env.py
import os

from pydantic_settings import BaseSettings


def export_settings_to_env(settings: BaseSettings):
    """
    Push all fields of a Pydantic settings object to os.environ,
    respecting env_prefix and envvar metadata. Supports nested models.
    """
    def recurse(obj, parent_prefix=""):
        # Get env prefix from this model, if any
        prefix = getattr(obj.model_config, "env_prefix", "") or ""
        prefix = parent_prefix + prefix

        for field_name, field_info in obj.model_fields.items():
            value = getattr(obj, field_name)
            if value is None:
                continue

            # Nested Pydantic model
            if hasattr(field_info.annotation, "model_fields"):
                recurse(value, parent_prefix=prefix)
            else:
                # Pull envvar from metadata if present
                envvar = None
                for k, v in getattr(field_info, 'metadata', ()):
                    if k == "envvar":
                        envvar = v
                        break

                env_name = envvar or (prefix + field_name.upper())
                os.environ[env_name] = str(value)

    recurse(settings)