from http import HTTPStatus
from typing import Any
from urllib.parse import quote

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.workflow_event import WorkflowEvent
from ...types import UNSET, Response, Unset


def _get_kwargs(
    workflow_id: str,
    run_rid: str,
    *,
    last_event_id_query: str | Unset = UNSET,
    last_event_id_header: str | Unset = UNSET,
) -> dict[str, Any]:
    headers: dict[str, Any] = {}
    if not isinstance(last_event_id_header, Unset):
        headers["Last-Event-ID"] = last_event_id_header

    params: dict[str, Any] = {}

    params["lastEventId"] = last_event_id_query

    params = {k: v for k, v in params.items() if v is not UNSET and v is not None}

    _kwargs: dict[str, Any] = {
        "method": "get",
        "url": "/api/v1/workflows/{workflow_id}/runs/{run_rid}/stream".format(
            workflow_id=quote(str(workflow_id), safe=""),
            run_rid=quote(str(run_rid), safe=""),
        ),
        "params": params,
    }

    _kwargs["headers"] = headers
    return _kwargs


def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> list[WorkflowEvent] | None:
    if response.status_code == 200:
        response_200 = []
        _response_200 = response.text
        for response_200_item_data in _response_200:
            response_200_item = WorkflowEvent.from_dict(response_200_item_data)

            response_200.append(response_200_item)

        return response_200

    if client.raise_on_unexpected_status:
        raise errors.UnexpectedStatus(response.status_code, response.content)
    else:
        return None


def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[list[WorkflowEvent]]:
    return Response(
        status_code=HTTPStatus(response.status_code),
        content=response.content,
        headers=response.headers,
        parsed=_parse_response(client=client, response=response),
    )


def sync_detailed(
    workflow_id: str,
    run_rid: str,
    *,
    client: AuthenticatedClient | Client,
    last_event_id_query: str | Unset = UNSET,
    last_event_id_header: str | Unset = UNSET,
) -> Response[list[WorkflowEvent]]:
    """Stream Events

    Args:
        workflow_id (str):
        run_rid (str):
        last_event_id_query (str | Unset):
        last_event_id_header (str | Unset):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Response[list[WorkflowEvent]]
    """

    kwargs = _get_kwargs(
        workflow_id=workflow_id,
        run_rid=run_rid,
        last_event_id_query=last_event_id_query,
        last_event_id_header=last_event_id_header,
    )

    response = client.get_httpx_client().request(
        **kwargs,
    )

    return _build_response(client=client, response=response)


def sync(
    workflow_id: str,
    run_rid: str,
    *,
    client: AuthenticatedClient | Client,
    last_event_id_query: str | Unset = UNSET,
    last_event_id_header: str | Unset = UNSET,
) -> list[WorkflowEvent] | None:
    """Stream Events

    Args:
        workflow_id (str):
        run_rid (str):
        last_event_id_query (str | Unset):
        last_event_id_header (str | Unset):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        list[WorkflowEvent]
    """

    return sync_detailed(
        workflow_id=workflow_id,
        run_rid=run_rid,
        client=client,
        last_event_id_query=last_event_id_query,
        last_event_id_header=last_event_id_header,
    ).parsed


async def asyncio_detailed(
    workflow_id: str,
    run_rid: str,
    *,
    client: AuthenticatedClient | Client,
    last_event_id_query: str | Unset = UNSET,
    last_event_id_header: str | Unset = UNSET,
) -> Response[list[WorkflowEvent]]:
    """Stream Events

    Args:
        workflow_id (str):
        run_rid (str):
        last_event_id_query (str | Unset):
        last_event_id_header (str | Unset):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Response[list[WorkflowEvent]]
    """

    kwargs = _get_kwargs(
        workflow_id=workflow_id,
        run_rid=run_rid,
        last_event_id_query=last_event_id_query,
        last_event_id_header=last_event_id_header,
    )

    response = await client.get_async_httpx_client().request(**kwargs)

    return _build_response(client=client, response=response)


async def asyncio(
    workflow_id: str,
    run_rid: str,
    *,
    client: AuthenticatedClient | Client,
    last_event_id_query: str | Unset = UNSET,
    last_event_id_header: str | Unset = UNSET,
) -> list[WorkflowEvent] | None:
    """Stream Events

    Args:
        workflow_id (str):
        run_rid (str):
        last_event_id_query (str | Unset):
        last_event_id_header (str | Unset):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        list[WorkflowEvent]
    """

    return (
        await asyncio_detailed(
            workflow_id=workflow_id,
            run_rid=run_rid,
            client=client,
            last_event_id_query=last_event_id_query,
            last_event_id_header=last_event_id_header,
        )
    ).parsed
