"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""

from importlib import import_module
import builtins
import sys


def dynamic_import(package, modname, retries=3):
    """Import a module relative to package, retrying on KeyError from half-initialized modules."""
    for attempt in range(retries):
        try:
            return import_module(modname, package)
        except KeyError:
            sys.modules.pop(modname, None)
            if attempt == retries - 1:
                break
    raise KeyError(f"Failed to import module '{modname}' after {retries} attempts")


def lazy_getattr(attr_name, *, package, dynamic_imports, sub_packages=None):
    """Module-level __getattr__ that lazily loads from a dynamic_imports mapping.

    Args:
        attr_name: The attribute being looked up.
        package: The caller's __package__ (for relative imports).
        dynamic_imports: Dict mapping attribute names to relative module paths.
        sub_packages: Optional list of subpackage names to lazy-load.
    """
    module_name = dynamic_imports.get(attr_name)
    if module_name is not None:
        try:
            module = dynamic_import(package, module_name)
            return getattr(module, attr_name)
        except ImportError as e:
            raise ImportError(
                f"Failed to import {attr_name} from {module_name}: {e}"
            ) from e
        except AttributeError as e:
            raise AttributeError(
                f"Failed to get {attr_name} from {module_name}: {e}"
            ) from e

    if sub_packages and attr_name in sub_packages:
        return import_module(f".{attr_name}", package)

    raise AttributeError(f"module '{package}' has no attribute '{attr_name}'")


def lazy_dir(*, dynamic_imports, sub_packages=None):
    """Module-level __dir__ that lists lazily-loadable attributes."""
    lazy_attrs = builtins.list(dynamic_imports.keys())
    if sub_packages:
        lazy_attrs.extend(sub_packages)
    return builtins.sorted(lazy_attrs)
