"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
# @generated-id: d23713342634

from typing import Any

from pydantic import BaseModel, TypeAdapter


def parse_open_union(
    v: Any,
    *,
    disc_key: str,
    variants: dict[str, Any],
    unknown_cls: type,
    union_name: str,
) -> 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 for inspection.
    """
    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")
    disc = v[disc_key]
    variant_cls = variants.get(disc)
    if variant_cls is not None:
        if isinstance(variant_cls, type) and issubclass(variant_cls, BaseModel):
            return variant_cls.model_validate(v)
        return TypeAdapter(variant_cls).validate_python(v)
    return unknown_cls(raw=v)
