{# NOTE: this template renders ONE function. It must be valid standalone python. #}

{% if async_client %}async {% endif %}def {{ operation_id }}(
    api_config_override: Optional[APIConfig] = None{% if params.strip() %}, *, {{ params.rstrip(', ') }}{% endif %}
) -> {% if is_sse %}{% if async_client %}AsyncGenerator[Any, None]{% else %}Iterator[Any]{% endif %}{% else %}{% if return_type.type is none or return_type.type.converted_type is none %}None{% else %}{{ return_type.type.converted_type }}{% endif %}{% endif %}:
    api_config = api_config_override if api_config_override else APIConfig()

    base_path = api_config.base_path
    path = f'{{ path_name }}'

    headers = {
        "Content-Type": "application/json",
{% if is_sse %}
        "Accept": "text/event-stream",
{% else %}
        "Accept": "application/json",
{% endif %}
        "Authorization": f"Bearer { api_config.get_access_token() }",
        {{ header_params | join(',\n') | safe }}
    }

    query_params: Dict[str, Any] = {}
    query_params = {key: value for (key, value) in query_params.items() if value is not None}

{% if is_sse %}
    import json

{% if async_client %}
    async with httpx.AsyncClient(base_url=base_path, verify=api_config.verify) as client:
        async with client.stream(
            "{{ method }}",
            httpx.URL(path),
            headers=headers,
            params=query_params,
{% if body_param %}
            json={{ body_param }},
{% endif %}
        ) as response:
            if response.status_code != {{ return_type.status_code }}:
                raise HTTPException(
                    response.status_code,
                    f"{{ operation_id }} failed with status code: {response.status_code}",
                )

            async for line in response.aiter_lines():
                if not line:
                    continue
                if line.startswith("data:"):
                    payload = line[len("data:"):].strip()
                    if not payload:
                        continue
                    if payload == "[DONE]":
                        break
                    try:
                        yield json.loads(payload)
                    except Exception:
                        yield payload
{% else %}
    with httpx.Client(base_url=base_path, verify=api_config.verify) as client:
        with client.stream(
            "{{ method }}",
            httpx.URL(path),
            headers=headers,
            params=query_params,
{% if body_param %}
            json={{ body_param }},
{% endif %}
        ) as response:
            if response.status_code != {{ return_type.status_code }}:
                raise HTTPException(
                    response.status_code,
                    f"{{ operation_id }} failed with status code: {response.status_code}",
                )

            for line in response.iter_lines():
                if not line:
                    continue
                if line.startswith("data:"):
                    payload = line[len("data:"):].strip()
                    if not payload:
                        continue
                    if payload == "[DONE]":
                        break
                    try:
                        yield json.loads(payload)
                    except Exception:
                        yield payload
{% endif %}

{% else %}
{% if async_client %}
    async with httpx.AsyncClient(base_url=base_path, verify=api_config.verify) as client:
        response = await client.request(
{% else %}
    with httpx.Client(base_url=base_path, verify=api_config.verify) as client:
        response = client.request(
{% endif %}
            "{{ method }}",
            httpx.URL(path),
            headers=headers,
            params=query_params,
{% if body_param %}
            json={{ body_param }},
{% endif %}
        )

    if response.status_code != {{ return_type.status_code }}:
        raise HTTPException(
            response.status_code,
            f"{{ operation_id }} failed with status code: {response.status_code}",
        )

    body = None if {{ return_type.status_code }} == 204 else response.json()

{% if return_type.type is none or return_type.type.converted_type is none %}
    return None
{% elif return_type.complex_type %}
{% if return_type.list_type is none %}
    return {{ return_type.type.converted_type }}(**body) if body is not None else {{ return_type.type.converted_type }}()
{% else %}
    return [{{ return_type.list_type }}(**item) for item in body]
{% endif %}
{% else %}
    return body
{% endif %}
{% endif %}