# 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.jsonable_encoder import jsonable_encoder
from ....core.parse_error import ParsingError
from ....core.request_options import RequestOptions
from ....core.unchecked_base_model import construct_type
from ....errors.unprocessable_entity_error import UnprocessableEntityError
from ....types.create_crawl_job_response_model import CreateCrawlJobResponseModel
from ....types.get_crawl_job_response_model import GetCrawlJobResponseModel
from ....types.list_crawl_jobs_response_model import ListCrawlJobsResponseModel
from pydantic import ValidationError

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


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

    def list(
        self,
        *,
        include_job_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        page_size: typing.Optional[int] = None,
        cursor: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ListCrawlJobsResponseModel]:
        """
        Get a list of ongoing and recent crawl jobs for the user.

        Parameters
        ----------
        include_job_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Ids of additional crawl jobs to retrieve

        page_size : typing.Optional[int]
            How many documents to return at maximum. Can not exceed 100, defaults to 30.

        cursor : typing.Optional[str]
            Used for fetching next page. Cursor is returned in the response.

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

        Returns
        -------
        HttpResponse[ListCrawlJobsResponseModel]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/convai/knowledge-base/crawl",
            method="GET",
            params={
                "include_job_ids": include_job_ids,
                "page_size": page_size,
                "cursor": cursor,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ListCrawlJobsResponseModel,
                    construct_type(
                        type_=ListCrawlJobsResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def create(
        self,
        *,
        url: str,
        max_depth: typing.Optional[int] = OMIT,
        max_pages: typing.Optional[int] = OMIT,
        pattern: typing.Optional[str] = OMIT,
        sitemap_urls: typing.Optional[typing.Sequence[str]] = OMIT,
        parent_folder_id: typing.Optional[str] = OMIT,
        enable_auto_sync: typing.Optional[bool] = OMIT,
        auto_remove: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[CreateCrawlJobResponseModel]:
        """
        Create a crawl job to crawl the given URL with specified depth and page limits.

        Parameters
        ----------
        url : str
            URL to a page of documentation that the agent will have access to in order to interact with users.

        max_depth : typing.Optional[int]
            Maximum depth for crawling (1-5), defaults to 3.

        max_pages : typing.Optional[int]
            Maximum number of pages to crawl (1-10,000), defaults to 1000.

        pattern : typing.Optional[str]
            If set, only URLs that match this pattern are included.

        sitemap_urls : typing.Optional[typing.Sequence[str]]
            List of URLs to crawl from sitemap (optional, overrides automatic URL discovery).

        parent_folder_id : typing.Optional[str]
            If set, the created document or folder will be placed inside the given folder.

        enable_auto_sync : typing.Optional[bool]
            Whether to enable auto-sync for this URL document.

        auto_remove : typing.Optional[bool]
            Whether to automatically remove the document if the URL becomes unavailable. Only applicable when auto-sync is enabled.

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

        Returns
        -------
        HttpResponse[CreateCrawlJobResponseModel]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/convai/knowledge-base/crawl",
            method="POST",
            json={
                "url": url,
                "max_depth": max_depth,
                "max_pages": max_pages,
                "pattern": pattern,
                "sitemap_urls": sitemap_urls,
                "parent_folder_id": parent_folder_id,
                "enable_auto_sync": enable_auto_sync,
                "auto_remove": auto_remove,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CreateCrawlJobResponseModel,
                    construct_type(
                        type_=CreateCrawlJobResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get(
        self, crawl_job_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[GetCrawlJobResponseModel]:
        """
        Get details about a specific crawl job including status and progress.

        Parameters
        ----------
        crawl_job_id : str
            The id of the crawl job to retrieve

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

        Returns
        -------
        HttpResponse[GetCrawlJobResponseModel]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/convai/knowledge-base/crawl/{jsonable_encoder(crawl_job_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetCrawlJobResponseModel,
                    construct_type(
                        type_=GetCrawlJobResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def cancel(
        self, crawl_job_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[typing.Any]:
        """
        Cancel a crawl job and delete all associated documents and folders.

        Parameters
        ----------
        crawl_job_id : str
            The id of the crawl job to retrieve

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

        Returns
        -------
        HttpResponse[typing.Any]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/convai/knowledge-base/crawl/{jsonable_encoder(crawl_job_id)}/cancel",
            method="POST",
            request_options=request_options,
        )
        try:
            if _response is None or not _response.text.strip():
                return HttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Any,
                    construct_type(
                        type_=typing.Any,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


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

    async def list(
        self,
        *,
        include_job_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        page_size: typing.Optional[int] = None,
        cursor: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ListCrawlJobsResponseModel]:
        """
        Get a list of ongoing and recent crawl jobs for the user.

        Parameters
        ----------
        include_job_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Ids of additional crawl jobs to retrieve

        page_size : typing.Optional[int]
            How many documents to return at maximum. Can not exceed 100, defaults to 30.

        cursor : typing.Optional[str]
            Used for fetching next page. Cursor is returned in the response.

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

        Returns
        -------
        AsyncHttpResponse[ListCrawlJobsResponseModel]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/convai/knowledge-base/crawl",
            method="GET",
            params={
                "include_job_ids": include_job_ids,
                "page_size": page_size,
                "cursor": cursor,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ListCrawlJobsResponseModel,
                    construct_type(
                        type_=ListCrawlJobsResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def create(
        self,
        *,
        url: str,
        max_depth: typing.Optional[int] = OMIT,
        max_pages: typing.Optional[int] = OMIT,
        pattern: typing.Optional[str] = OMIT,
        sitemap_urls: typing.Optional[typing.Sequence[str]] = OMIT,
        parent_folder_id: typing.Optional[str] = OMIT,
        enable_auto_sync: typing.Optional[bool] = OMIT,
        auto_remove: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[CreateCrawlJobResponseModel]:
        """
        Create a crawl job to crawl the given URL with specified depth and page limits.

        Parameters
        ----------
        url : str
            URL to a page of documentation that the agent will have access to in order to interact with users.

        max_depth : typing.Optional[int]
            Maximum depth for crawling (1-5), defaults to 3.

        max_pages : typing.Optional[int]
            Maximum number of pages to crawl (1-10,000), defaults to 1000.

        pattern : typing.Optional[str]
            If set, only URLs that match this pattern are included.

        sitemap_urls : typing.Optional[typing.Sequence[str]]
            List of URLs to crawl from sitemap (optional, overrides automatic URL discovery).

        parent_folder_id : typing.Optional[str]
            If set, the created document or folder will be placed inside the given folder.

        enable_auto_sync : typing.Optional[bool]
            Whether to enable auto-sync for this URL document.

        auto_remove : typing.Optional[bool]
            Whether to automatically remove the document if the URL becomes unavailable. Only applicable when auto-sync is enabled.

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

        Returns
        -------
        AsyncHttpResponse[CreateCrawlJobResponseModel]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/convai/knowledge-base/crawl",
            method="POST",
            json={
                "url": url,
                "max_depth": max_depth,
                "max_pages": max_pages,
                "pattern": pattern,
                "sitemap_urls": sitemap_urls,
                "parent_folder_id": parent_folder_id,
                "enable_auto_sync": enable_auto_sync,
                "auto_remove": auto_remove,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CreateCrawlJobResponseModel,
                    construct_type(
                        type_=CreateCrawlJobResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get(
        self, crawl_job_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[GetCrawlJobResponseModel]:
        """
        Get details about a specific crawl job including status and progress.

        Parameters
        ----------
        crawl_job_id : str
            The id of the crawl job to retrieve

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

        Returns
        -------
        AsyncHttpResponse[GetCrawlJobResponseModel]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/convai/knowledge-base/crawl/{jsonable_encoder(crawl_job_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetCrawlJobResponseModel,
                    construct_type(
                        type_=GetCrawlJobResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def cancel(
        self, crawl_job_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[typing.Any]:
        """
        Cancel a crawl job and delete all associated documents and folders.

        Parameters
        ----------
        crawl_job_id : str
            The id of the crawl job to retrieve

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

        Returns
        -------
        AsyncHttpResponse[typing.Any]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/convai/knowledge-base/crawl/{jsonable_encoder(crawl_job_id)}/cancel",
            method="POST",
            request_options=request_options,
        )
        try:
            if _response is None or not _response.text.strip():
                return AsyncHttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Any,
                    construct_type(
                        type_=typing.Any,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
