# This file was auto-generated by Fern from our API Definition.

import typing
from json.decoder import JSONDecodeError

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..core.serialization import convert_and_respect_annotation_metadata
from ..errors.conflict_error import ConflictError
from ..errors.unauthorized_error import UnauthorizedError
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.mini_chat_settings_payload import MiniChatSettingsPayload
from ..types.mini_chat_settings_response import MiniChatSettingsResponse

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class RawUserPreferencesClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def get_mini_chat_settings(
        self, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[MiniChatSettingsResponse]:
        """
        Retrieve the authenticated user's mini chat bar settings.

        **First-run behaviour:** If no settings have been saved yet, the server
        auto-provisions canonical defaults and returns them with `revision: 1`.
        The endpoint **always** returns `200`; it never returns `404`.

        **Response envelope:**

        ```json
        {
          "data": {
            "settings": { ... },
            "revision": 1,
            "updatedAt": "2026-03-02T09:30:00Z"
          }
        }
        ```

        Parameters
        ----------
        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[MiniChatSettingsResponse]
            Settings retrieved (or auto-provisioned on first access)
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/users/me/preferences/mini-chat",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    MiniChatSettingsResponse,
                    parse_obj_as(
                        type_=MiniChatSettingsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def upsert_mini_chat_settings(
        self,
        *,
        settings: MiniChatSettingsPayload,
        revision: int,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[MiniChatSettingsResponse]:
        """
        Create or update the authenticated user's mini chat bar settings using
        **optimistic concurrency** based on a monotonic `revision` counter.

        ### Request

        | Field | Type | Required | Description |
        |-------|------|----------|-------------|
        | `settings` | object | yes | Full settings object (missing fields default to canonical values) |
        | `revision` | integer | yes | The revision the client last read; must match server's current revision |

        ### Settings fields

        | Field | Type | Allowed values | Default |
        |-------|------|----------------|---------|
        | `position` | string | `bottom-right`, `bottom-left`, `top-right`, `top-left`, `bottom-center`, `top-center` | `bottom-center` |
        | `resetToNewChat` | string | `never`, `10m`, `30m`, `60m` | `10m` |
        | `keyboardShortcut` | string | any string (trimmed; whitespace-only becomes `""`) | `CommandOrControl+K` |
        | `openNewChats` | string | `companion-chat`, `main-window` | `companion-chat` |
        | `assistantSelection` | string | `default`, `last-used` | `default` |

        ### Conflict handling

        If the client sends a stale `revision`, the server responds with **409**
        and includes the latest canonical state in `error.details.latest` so the
        client can re-hydrate without an extra GET.

        ### Normalization

        - Unknown fields in `settings` are silently ignored.
        - Missing fields are filled with defaults (full-replace semantics).
        - `keyboardShortcut` is trimmed; whitespace-only becomes `""`.

        Parameters
        ----------
        settings : MiniChatSettingsPayload
            Full settings object (missing fields filled with defaults)

        revision : int
            Expected current revision for optimistic concurrency. Send 0 when writing for the first time (no prior GET).

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[MiniChatSettingsResponse]
            Settings saved successfully
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/users/me/preferences/mini-chat",
            method="PUT",
            json={
                "settings": convert_and_respect_annotation_metadata(
                    object_=settings, annotation=MiniChatSettingsPayload, direction="write"
                ),
                "revision": revision,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    MiniChatSettingsResponse,
                    parse_obj_as(
                        type_=MiniChatSettingsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 409:
                raise ConflictError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


class AsyncRawUserPreferencesClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def get_mini_chat_settings(
        self, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[MiniChatSettingsResponse]:
        """
        Retrieve the authenticated user's mini chat bar settings.

        **First-run behaviour:** If no settings have been saved yet, the server
        auto-provisions canonical defaults and returns them with `revision: 1`.
        The endpoint **always** returns `200`; it never returns `404`.

        **Response envelope:**

        ```json
        {
          "data": {
            "settings": { ... },
            "revision": 1,
            "updatedAt": "2026-03-02T09:30:00Z"
          }
        }
        ```

        Parameters
        ----------
        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[MiniChatSettingsResponse]
            Settings retrieved (or auto-provisioned on first access)
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/users/me/preferences/mini-chat",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    MiniChatSettingsResponse,
                    parse_obj_as(
                        type_=MiniChatSettingsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def upsert_mini_chat_settings(
        self,
        *,
        settings: MiniChatSettingsPayload,
        revision: int,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[MiniChatSettingsResponse]:
        """
        Create or update the authenticated user's mini chat bar settings using
        **optimistic concurrency** based on a monotonic `revision` counter.

        ### Request

        | Field | Type | Required | Description |
        |-------|------|----------|-------------|
        | `settings` | object | yes | Full settings object (missing fields default to canonical values) |
        | `revision` | integer | yes | The revision the client last read; must match server's current revision |

        ### Settings fields

        | Field | Type | Allowed values | Default |
        |-------|------|----------------|---------|
        | `position` | string | `bottom-right`, `bottom-left`, `top-right`, `top-left`, `bottom-center`, `top-center` | `bottom-center` |
        | `resetToNewChat` | string | `never`, `10m`, `30m`, `60m` | `10m` |
        | `keyboardShortcut` | string | any string (trimmed; whitespace-only becomes `""`) | `CommandOrControl+K` |
        | `openNewChats` | string | `companion-chat`, `main-window` | `companion-chat` |
        | `assistantSelection` | string | `default`, `last-used` | `default` |

        ### Conflict handling

        If the client sends a stale `revision`, the server responds with **409**
        and includes the latest canonical state in `error.details.latest` so the
        client can re-hydrate without an extra GET.

        ### Normalization

        - Unknown fields in `settings` are silently ignored.
        - Missing fields are filled with defaults (full-replace semantics).
        - `keyboardShortcut` is trimmed; whitespace-only becomes `""`.

        Parameters
        ----------
        settings : MiniChatSettingsPayload
            Full settings object (missing fields filled with defaults)

        revision : int
            Expected current revision for optimistic concurrency. Send 0 when writing for the first time (no prior GET).

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[MiniChatSettingsResponse]
            Settings saved successfully
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/users/me/preferences/mini-chat",
            method="PUT",
            json={
                "settings": convert_and_respect_annotation_metadata(
                    object_=settings, annotation=MiniChatSettingsPayload, direction="write"
                ),
                "revision": revision,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    MiniChatSettingsResponse,
                    parse_obj_as(
                        type_=MiniChatSettingsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 409:
                raise ConflictError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
