# 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
# pylint: skip-file

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

from functools import partial
from typing import Any, Mapping, Optional

from pydantic import (
    BaseModel,
    TypeAdapter,
    ValidationError,
    ValidationInfo,
    ValidatorFunctionWrapHandler,
)
from typing_extensions import Annotated, get_args, get_origin


def parse_open_union(
    v: Any,
    info: ValidationInfo,
    *,
    disc_key: str,
    variants: dict[str, Any],
    unknown_cls: type,
    union_name: str,
    lenient: bool = False,
) -> Any:
    """Parse an open discriminated union value with forward-compatibility.

    Known discriminator values are dispatched to their variant types.

    Unknown discriminator values produce an instance of the fallback class,
    preserving the raw payload, which serializes back unchanged. This applies
    to server responses and to request payloads alike.

    Known discriminator values whose payload fails variant validation (e.g. a
    partial variant emitted by a newer server) also produce the fallback
    class, but only when the validation context carries
    ALLOW_UNKNOWN_UNION_VARIANTS, which the SDK sets when deserializing
    server responses. Without the flag (e.g. user-constructed request
    payloads), they raise so mistakes surface locally instead of being sent
    to the server.

    Non-dict values and dicts missing the discriminator deliberately raise
    instead of falling back, so pydantic can try sibling branches of an
    enclosing union (e.g. None in Optional[...]).
    """
    # pylint: disable=import-outside-toplevel
    from .serializers import ALLOW_UNKNOWN_UNION_VARIANTS

    if isinstance(v, BaseModel):
        return v
    if not isinstance(v, dict) or disc_key not in v:
        raise ValueError(f"{union_name}: expected object with '{disc_key}' field")
    context = info.context
    fallback_allowed = isinstance(context, Mapping) and bool(
        context.get(ALLOW_UNKNOWN_UNION_VARIANTS)
    )
    disc = v[disc_key]
    variant_cls = variants.get(disc)
    if variant_cls is None:
        return unknown_cls(raw=v)
    try:
        if isinstance(variant_cls, type) and issubclass(variant_cls, BaseModel):
            return variant_cls.model_validate(v, context=info.context)
        return TypeAdapter(variant_cls).validate_python(v, context=info.context)
    except ValidationError:
        if not fallback_allowed:
            raise
        if lenient:
            # pylint: disable=import-outside-toplevel
            from .serializers import construct_unvalidated

            return construct_unvalidated(v, variant_cls)
        return unknown_cls(raw=v)


def decline_sibling_variants(
    value: Any,
    handler: ValidatorFunctionWrapHandler,
    info: ValidationInfo,
    *,
    union_name: str,
    sibling_variants: tuple[tuple[str, frozenset[str]], ...],
) -> Any:
    """Validate an open union member of an enclosing non-discriminated union.

    Outside server responses, the Unknown fallback is declined for a value
    whose discriminator another open union member of the enclosing union
    recognizes (sibling_variants: per discriminator property, the values of
    those members), so the enclosing union selects a different member.
    """
    # pylint: disable=import-outside-toplevel
    from .serializers import ALLOW_UNKNOWN_UNION_VARIANTS

    result = handler(value)
    context = info.context
    if (
        getattr(result, "is_unknown", False) is not True
        or not isinstance(value, dict)
        or (
            isinstance(context, Mapping)
            and bool(context.get(ALLOW_UNKNOWN_UNION_VARIANTS))
        )
    ):
        return result
    for key, values in sibling_variants:
        disc = value.get(key)
        if isinstance(disc, str) and disc in values:
            raise ValueError(
                f"{union_name}: {key} value {disc!r} belongs to another member of the enclosing union"
            )
    return result


_DispatchMember = tuple[int, Optional[type], str, Mapping[str, Any]]

_DISPATCH_MEMBERS: dict[int, tuple[tuple[Any, ...], list[_DispatchMember]]] = {}
_DISPATCH_ADAPTERS: dict[int, tuple[Any, TypeAdapter]] = {}


def _open_union_keywords(tp: Any) -> Optional[Mapping[str, Any]]:
    if get_origin(tp) is not Annotated:
        return None
    for metadata in get_args(tp)[1:]:
        func = getattr(metadata, "func", None)
        if isinstance(func, partial) and func.func is parse_open_union:
            return func.keywords
    return None


def _dispatch_members(members: tuple[Any, ...]) -> list[_DispatchMember]:
    cached = _DISPATCH_MEMBERS.get(id(members))
    if cached is not None:
        return cached[1]
    described: list[_DispatchMember] = []
    for index, member in enumerate(members):
        container = get_origin(member)
        if container in (list, dict):
            item = get_args(member)[-1]
        else:
            container, item = None, member
        keywords = _open_union_keywords(item)
        if keywords is not None:
            described.append(
                (index, container, keywords["disc_key"], keywords["variants"])
            )
    _DISPATCH_MEMBERS[id(members)] = (members, described)
    return described


def _recognizes(item: Any, disc_key: str, variants: Mapping[str, Any]) -> bool:
    if not isinstance(item, dict):
        return False
    disc = item.get(disc_key)
    return isinstance(disc, str) and disc in variants


def _container_owners(
    container: type, items: list[Any], described: list[_DispatchMember]
) -> list[int]:
    candidates = [
        member
        for member in described
        if member[1] is container
        and all(isinstance(item, dict) and member[2] in item for item in items)
    ]
    recognized = [
        {
            index
            for index, _, disc_key, variants in candidates
            if _recognizes(item, disc_key, variants)
        }
        for item in items
    ]
    return [
        index
        for index, _, _, _ in candidates
        if any(index in owners for owners in recognized)
        and all(index in owners for owners in recognized if owners)
    ]


def _owning_member(value: Any, described: list[_DispatchMember]) -> Optional[int]:
    if isinstance(value, dict):
        owners = [
            index
            for index, container, disc_key, variants in described
            if container is None and _recognizes(value, disc_key, variants)
        ]
        owners += _container_owners(dict, list(value.values()), described)
    elif isinstance(value, list):
        owners = _container_owners(list, value, described)
    else:
        return None
    return owners[0] if len(owners) == 1 else None


def _dispatch_adapter(member: Any) -> TypeAdapter:
    cached = _DISPATCH_ADAPTERS.get(id(member))
    if cached is None:
        cached = (member, TypeAdapter(member))
        _DISPATCH_ADAPTERS[id(member)] = cached
    return cached[1]


def dispatch_open_union_members(
    value: Any,
    handler: ValidatorFunctionWrapHandler,
    info: ValidationInfo,
    *,
    members: tuple[Any, ...],
) -> Any:
    """Validate a union value against the open discriminated union that owns it.

    members lists the union's open discriminated unions, directly or as list or
    dict items. An object belongs to the members whose discriminator mapping
    contains its discriminator value. A list or dict belongs to a container
    member when every item is an object with that member's discriminator field,
    and that member recognizes at least one item and every recognized item.
    With exactly one owner, the value is validated against that member first,
    so another member's Unknown fallback cannot claim it. Otherwise, or when
    the owner rejects the value, the enclosing union validates the value as
    usual; if that also fails, the owner's error is raised.
    """
    owner = _owning_member(value, _dispatch_members(members))
    if owner is None:
        return handler(value)
    try:
        return _dispatch_adapter(members[owner]).validate_python(
            value, context=info.context
        )
    except ValidationError as owner_error:
        try:
            return handler(value)
        except ValidationError:
            raise owner_error from None
