# 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 enum import Enum
from typing import Any, Optional


def get_discriminator(model: Any, fieldname: str, key: str) -> str:
    """
    Recursively search for the discriminator attribute in a model.

    Args:
        model (Any): The model to search within.
        fieldname (str): The name of the field to search for.
        key (str): The key to search for in dictionaries.

    Returns:
        str: The name of the discriminator attribute.

    Raises:
        ValueError: If the discriminator attribute is not found.
    """
    upper_fieldname = fieldname.upper()

    def get_field_discriminator(field: Any) -> Optional[str]:
        """Search for the discriminator attribute in a given field."""

        if isinstance(field, dict):
            if key in field:
                return f"{field[key]}"

        if hasattr(field, fieldname):
            attr = getattr(field, fieldname)
            if isinstance(attr, Enum):
                return f"{attr.value}"
            return f"{attr}"

        if hasattr(field, upper_fieldname):
            attr = getattr(field, upper_fieldname)
            if isinstance(attr, Enum):
                return f"{attr.value}"
            return f"{attr}"

        return None

    def search_nested_discriminator(obj: Any) -> Optional[str]:
        """Recursively search for discriminator in nested structures."""
        # First try direct field lookup
        discriminator = get_field_discriminator(obj)
        if discriminator is not None:
            return discriminator

        # If it's a dict, search in nested values
        if isinstance(obj, dict):
            for value in obj.values():
                if isinstance(value, list):
                    # Search in list items
                    for item in value:
                        nested_discriminator = search_nested_discriminator(item)
                        if nested_discriminator is not None:
                            return nested_discriminator
                elif isinstance(value, dict):
                    # Search in nested dict
                    nested_discriminator = search_nested_discriminator(value)
                    if nested_discriminator is not None:
                        return nested_discriminator

        return None

    if isinstance(model, list):
        for field in model:
            discriminator = search_nested_discriminator(field)
            if discriminator is not None:
                return discriminator

    discriminator = search_nested_discriminator(model)
    if discriminator is not None:
        return discriminator

    raise ValueError(f"Could not find discriminator field {fieldname} in {model}")
