# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# pyformat: disable

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

from importlib import import_module, util
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:
            resolved = util.resolve_name(modname, package)
            sys.modules.pop(resolved, 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)
