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

import httpx

from ...client import AuthenticatedClient, Client
from ...types import Response, UNSET
from ... import errors

from ...models.http_validation_error import HTTPValidationError
from ...models.workspace_open_request import WorkspaceOpenRequest
from ...models.workspace_open_response import WorkspaceOpenResponse
from typing import cast



def _get_kwargs(
    workspace_ext_id: str,
    *,
    body: WorkspaceOpenRequest,

) -> dict[str, Any]:
    headers: dict[str, Any] = {}


    

    

    _kwargs: dict[str, Any] = {
        "method": "post",
        "url": "/v1/workspace/{workspace_ext_id}/open".format(workspace_ext_id=quote(str(workspace_ext_id), safe=""),),
    }

    _kwargs["json"] = body.to_dict()


    headers["Content-Type"] = "application/json"

    _kwargs["headers"] = headers
    return _kwargs



def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> HTTPValidationError | WorkspaceOpenResponse | None:
    if response.status_code == 200:
        response_200 = WorkspaceOpenResponse.from_dict(response.json())



        return response_200

    if response.status_code == 422:
        response_422 = HTTPValidationError.from_dict(response.json())



        return response_422

    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[HTTPValidationError | WorkspaceOpenResponse]:
    return Response(
        status_code=HTTPStatus(response.status_code),
        content=response.content,
        headers=response.headers,
        parsed=_parse_response(client=client, response=response),
    )


def sync_detailed(
    workspace_ext_id: str,
    *,
    client: AuthenticatedClient | Client,
    body: WorkspaceOpenRequest,

) -> Response[HTTPValidationError | WorkspaceOpenResponse]:
    """ Open Workspace

     Open a workspace: store encrypted workspace key in session, set active, return workspace data.

    Users provide ``workspace_key`` (SealedBox-encrypted with session public key).
    Agents omit it — their workspace keys are pre-populated at login from their WorkspaceUsers rows.

    Args:
        workspace_ext_id (str):
        body (WorkspaceOpenRequest): Request to open a workspace — stores encrypted key in session
            and sets active.

            workspace_key is required for users (SealedBox-encrypted with session public key).
            Agents omit it — their workspace keys are pre-populated via /agent-session.

    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[HTTPValidationError | WorkspaceOpenResponse]
     """


    kwargs = _get_kwargs(
        workspace_ext_id=workspace_ext_id,
body=body,

    )

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

    return _build_response(client=client, response=response)

def sync(
    workspace_ext_id: str,
    *,
    client: AuthenticatedClient | Client,
    body: WorkspaceOpenRequest,

) -> HTTPValidationError | WorkspaceOpenResponse | None:
    """ Open Workspace

     Open a workspace: store encrypted workspace key in session, set active, return workspace data.

    Users provide ``workspace_key`` (SealedBox-encrypted with session public key).
    Agents omit it — their workspace keys are pre-populated at login from their WorkspaceUsers rows.

    Args:
        workspace_ext_id (str):
        body (WorkspaceOpenRequest): Request to open a workspace — stores encrypted key in session
            and sets active.

            workspace_key is required for users (SealedBox-encrypted with session public key).
            Agents omit it — their workspace keys are pre-populated via /agent-session.

    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:
        HTTPValidationError | WorkspaceOpenResponse
     """


    return sync_detailed(
        workspace_ext_id=workspace_ext_id,
client=client,
body=body,

    ).parsed

async def asyncio_detailed(
    workspace_ext_id: str,
    *,
    client: AuthenticatedClient | Client,
    body: WorkspaceOpenRequest,

) -> Response[HTTPValidationError | WorkspaceOpenResponse]:
    """ Open Workspace

     Open a workspace: store encrypted workspace key in session, set active, return workspace data.

    Users provide ``workspace_key`` (SealedBox-encrypted with session public key).
    Agents omit it — their workspace keys are pre-populated at login from their WorkspaceUsers rows.

    Args:
        workspace_ext_id (str):
        body (WorkspaceOpenRequest): Request to open a workspace — stores encrypted key in session
            and sets active.

            workspace_key is required for users (SealedBox-encrypted with session public key).
            Agents omit it — their workspace keys are pre-populated via /agent-session.

    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[HTTPValidationError | WorkspaceOpenResponse]
     """


    kwargs = _get_kwargs(
        workspace_ext_id=workspace_ext_id,
body=body,

    )

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

    return _build_response(client=client, response=response)

async def asyncio(
    workspace_ext_id: str,
    *,
    client: AuthenticatedClient | Client,
    body: WorkspaceOpenRequest,

) -> HTTPValidationError | WorkspaceOpenResponse | None:
    """ Open Workspace

     Open a workspace: store encrypted workspace key in session, set active, return workspace data.

    Users provide ``workspace_key`` (SealedBox-encrypted with session public key).
    Agents omit it — their workspace keys are pre-populated at login from their WorkspaceUsers rows.

    Args:
        workspace_ext_id (str):
        body (WorkspaceOpenRequest): Request to open a workspace — stores encrypted key in session
            and sets active.

            workspace_key is required for users (SealedBox-encrypted with session public key).
            Agents omit it — their workspace keys are pre-populated via /agent-session.

    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:
        HTTPValidationError | WorkspaceOpenResponse
     """


    return (await asyncio_detailed(
        workspace_ext_id=workspace_ext_id,
client=client,
body=body,

    )).parsed
