# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.

from __future__ import annotations

from typing import Dict, List, Union
from datetime import datetime
from typing_extensions import Literal

import httpx

from .tags import (
    TagsResource,
    AsyncTagsResource,
    TagsResourceWithRawResponse,
    AsyncTagsResourceWithRawResponse,
    TagsResourceWithStreamingResponse,
    AsyncTagsResourceWithStreamingResponse,
)
from ...types import document_list_params, document_create_params
from ..._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given
from ..._utils import maybe_transform, async_maybe_transform
from .versions import (
    VersionsResource,
    AsyncVersionsResource,
    VersionsResourceWithRawResponse,
    AsyncVersionsResourceWithRawResponse,
    VersionsResourceWithStreamingResponse,
    AsyncVersionsResourceWithStreamingResponse,
)
from ..._compat import cached_property
from ..._resource import SyncAPIResource, AsyncAPIResource
from ..._response import (
    to_raw_response_wrapper,
    to_streamed_response_wrapper,
    async_to_raw_response_wrapper,
    async_to_streamed_response_wrapper,
)
from ...pagination import SyncOffsetPagination, AsyncOffsetPagination
from ..._base_client import AsyncPaginator, make_request_options
from ...types.document_list_response import DocumentListResponse
from ...types.document_create_response import DocumentCreateResponse
from ...types.document_activate_response import DocumentActivateResponse
from ...types.document_retrieve_response import DocumentRetrieveResponse

__all__ = ["DocumentsResource", "AsyncDocumentsResource"]


class DocumentsResource(SyncAPIResource):
    @cached_property
    def versions(self) -> VersionsResource:
        return VersionsResource(self._client)

    @cached_property
    def tags(self) -> TagsResource:
        return TagsResource(self._client)

    @cached_property
    def with_raw_response(self) -> DocumentsResourceWithRawResponse:
        """
        This property can be used as a prefix for any HTTP method call to return
        the raw response object instead of the parsed content.

        For more information, see https://www.github.com/Avido-AI/avido-py#accessing-raw-response-data-eg-headers
        """
        return DocumentsResourceWithRawResponse(self)

    @cached_property
    def with_streaming_response(self) -> DocumentsResourceWithStreamingResponse:
        """
        An alternative to `.with_raw_response` that doesn't eagerly read the response body.

        For more information, see https://www.github.com/Avido-AI/avido-py#with_streaming_response
        """
        return DocumentsResourceWithStreamingResponse(self)

    def create(
        self,
        *,
        content: str,
        title: str,
        assignee: str | Omit = omit,
        language: str | Omit = omit,
        metadata: Dict[str, object] | Omit = omit,
        original_sentences: SequenceNotStr[str] | Omit = omit,
        quickstart_id: str | Omit = omit,
        scrape_job_id: str | Omit = omit,
        status: Literal["DRAFT", "REVIEW", "APPROVED", "ARCHIVED", "ACTIVE"] | Omit = omit,
        topic_id: str | Omit = omit,
        type: Literal["KNOWLEDGE", "POLICY"] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DocumentCreateResponse:
        """
        Creates a new document with the provided information.

        Args:
          content: Content of the initial document version

          title: Title of the initial document version

          assignee: User ID of the person assigned to this document. Defaults to the authenticated
              user if not provided.

          language: Language of the initial document version

          metadata: Optional metadata for the initial document version

          original_sentences: Array of original sentences from the source

          quickstart_id: Optional ID of the QuickstartV2 this document belongs to

          scrape_job_id: Optional ID of the scrape job that generated this document

          status: Status of the initial document version

          topic_id: Optional ID of the topic this document belongs to

          type: Type of the document. Defaults to KNOWLEDGE.

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._post(
            "/v0/documents",
            body=maybe_transform(
                {
                    "content": content,
                    "title": title,
                    "assignee": assignee,
                    "language": language,
                    "metadata": metadata,
                    "original_sentences": original_sentences,
                    "quickstart_id": quickstart_id,
                    "scrape_job_id": scrape_job_id,
                    "status": status,
                    "topic_id": topic_id,
                    "type": type,
                },
                document_create_params.DocumentCreateParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DocumentCreateResponse,
        )

    def retrieve(
        self,
        id: str,
        *,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DocumentRetrieveResponse:
        """
        Retrieves detailed information about a specific document, including its
        parent-child relationships and active version details.

        Args:
          id: The unique identifier of the document

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not id:
            raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
        return self._get(
            f"/v0/documents/{id}",
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DocumentRetrieveResponse,
        )

    def list(
        self,
        *,
        assignee: str | Omit = omit,
        end_date: Union[str, datetime] | Omit = omit,
        limit: int | Omit = omit,
        order_by: str | Omit = omit,
        order_dir: Literal["asc", "desc"] | Omit = omit,
        scrape_job_id: SequenceNotStr[str] | Omit = omit,
        search: str | Omit = omit,
        skip: int | Omit = omit,
        start_date: Union[str, datetime] | Omit = omit,
        status: List[Literal["DRAFT", "REVIEW", "APPROVED", "ARCHIVED", "ACTIVE"]] | Omit = omit,
        tag_id: SequenceNotStr[str] | Omit = omit,
        type: Literal["KNOWLEDGE", "POLICY"] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> SyncOffsetPagination[DocumentListResponse]:
        """
        Retrieves a paginated list of documents with optional filtering by status,
        assignee, parent, and other criteria. Only returns documents with active
        approved versions unless otherwise specified.

        Args:
          assignee: Filter by assignee user ID

          end_date: Filter documents created before this date (inclusive).

          limit: Number of items to include in the result set.

          order_by: Field to order by in the result set.

          order_dir: Order direction.

          scrape_job_id: Filter by scrape job ID. Supports multiple values.

          search: Search in document version title and content

          skip: Number of items to skip before starting to collect the result set.

          start_date: Filter documents created after this date (inclusive).

          status: Filter by document version status (filters documents by their active version
              status). Supports multiple values.

          tag_id: Filter documents by tag ID

          type: Filter by document type. Defaults to KNOWLEDGE if not specified.

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._get_api_list(
            "/v0/documents",
            page=SyncOffsetPagination[DocumentListResponse],
            options=make_request_options(
                extra_headers=extra_headers,
                extra_query=extra_query,
                extra_body=extra_body,
                timeout=timeout,
                query=maybe_transform(
                    {
                        "assignee": assignee,
                        "end_date": end_date,
                        "limit": limit,
                        "order_by": order_by,
                        "order_dir": order_dir,
                        "scrape_job_id": scrape_job_id,
                        "search": search,
                        "skip": skip,
                        "start_date": start_date,
                        "status": status,
                        "tag_id": tag_id,
                        "type": type,
                    },
                    document_list_params.DocumentListParams,
                ),
            ),
            model=DocumentListResponse,
        )

    def activate(
        self,
        version_number: int,
        *,
        id: str,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DocumentActivateResponse:
        """Makes a specific version the active version of a document.

        This is the version
        that will be returned by default when fetching the document.

        Args:
          id: The unique identifier of the document

          version_number: The version number

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not id:
            raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
        return self._put(
            f"/v0/documents/{id}/versions/{version_number}/activate",
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DocumentActivateResponse,
        )


class AsyncDocumentsResource(AsyncAPIResource):
    @cached_property
    def versions(self) -> AsyncVersionsResource:
        return AsyncVersionsResource(self._client)

    @cached_property
    def tags(self) -> AsyncTagsResource:
        return AsyncTagsResource(self._client)

    @cached_property
    def with_raw_response(self) -> AsyncDocumentsResourceWithRawResponse:
        """
        This property can be used as a prefix for any HTTP method call to return
        the raw response object instead of the parsed content.

        For more information, see https://www.github.com/Avido-AI/avido-py#accessing-raw-response-data-eg-headers
        """
        return AsyncDocumentsResourceWithRawResponse(self)

    @cached_property
    def with_streaming_response(self) -> AsyncDocumentsResourceWithStreamingResponse:
        """
        An alternative to `.with_raw_response` that doesn't eagerly read the response body.

        For more information, see https://www.github.com/Avido-AI/avido-py#with_streaming_response
        """
        return AsyncDocumentsResourceWithStreamingResponse(self)

    async def create(
        self,
        *,
        content: str,
        title: str,
        assignee: str | Omit = omit,
        language: str | Omit = omit,
        metadata: Dict[str, object] | Omit = omit,
        original_sentences: SequenceNotStr[str] | Omit = omit,
        quickstart_id: str | Omit = omit,
        scrape_job_id: str | Omit = omit,
        status: Literal["DRAFT", "REVIEW", "APPROVED", "ARCHIVED", "ACTIVE"] | Omit = omit,
        topic_id: str | Omit = omit,
        type: Literal["KNOWLEDGE", "POLICY"] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DocumentCreateResponse:
        """
        Creates a new document with the provided information.

        Args:
          content: Content of the initial document version

          title: Title of the initial document version

          assignee: User ID of the person assigned to this document. Defaults to the authenticated
              user if not provided.

          language: Language of the initial document version

          metadata: Optional metadata for the initial document version

          original_sentences: Array of original sentences from the source

          quickstart_id: Optional ID of the QuickstartV2 this document belongs to

          scrape_job_id: Optional ID of the scrape job that generated this document

          status: Status of the initial document version

          topic_id: Optional ID of the topic this document belongs to

          type: Type of the document. Defaults to KNOWLEDGE.

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return await self._post(
            "/v0/documents",
            body=await async_maybe_transform(
                {
                    "content": content,
                    "title": title,
                    "assignee": assignee,
                    "language": language,
                    "metadata": metadata,
                    "original_sentences": original_sentences,
                    "quickstart_id": quickstart_id,
                    "scrape_job_id": scrape_job_id,
                    "status": status,
                    "topic_id": topic_id,
                    "type": type,
                },
                document_create_params.DocumentCreateParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DocumentCreateResponse,
        )

    async def retrieve(
        self,
        id: str,
        *,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DocumentRetrieveResponse:
        """
        Retrieves detailed information about a specific document, including its
        parent-child relationships and active version details.

        Args:
          id: The unique identifier of the document

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not id:
            raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
        return await self._get(
            f"/v0/documents/{id}",
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DocumentRetrieveResponse,
        )

    def list(
        self,
        *,
        assignee: str | Omit = omit,
        end_date: Union[str, datetime] | Omit = omit,
        limit: int | Omit = omit,
        order_by: str | Omit = omit,
        order_dir: Literal["asc", "desc"] | Omit = omit,
        scrape_job_id: SequenceNotStr[str] | Omit = omit,
        search: str | Omit = omit,
        skip: int | Omit = omit,
        start_date: Union[str, datetime] | Omit = omit,
        status: List[Literal["DRAFT", "REVIEW", "APPROVED", "ARCHIVED", "ACTIVE"]] | Omit = omit,
        tag_id: SequenceNotStr[str] | Omit = omit,
        type: Literal["KNOWLEDGE", "POLICY"] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> AsyncPaginator[DocumentListResponse, AsyncOffsetPagination[DocumentListResponse]]:
        """
        Retrieves a paginated list of documents with optional filtering by status,
        assignee, parent, and other criteria. Only returns documents with active
        approved versions unless otherwise specified.

        Args:
          assignee: Filter by assignee user ID

          end_date: Filter documents created before this date (inclusive).

          limit: Number of items to include in the result set.

          order_by: Field to order by in the result set.

          order_dir: Order direction.

          scrape_job_id: Filter by scrape job ID. Supports multiple values.

          search: Search in document version title and content

          skip: Number of items to skip before starting to collect the result set.

          start_date: Filter documents created after this date (inclusive).

          status: Filter by document version status (filters documents by their active version
              status). Supports multiple values.

          tag_id: Filter documents by tag ID

          type: Filter by document type. Defaults to KNOWLEDGE if not specified.

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._get_api_list(
            "/v0/documents",
            page=AsyncOffsetPagination[DocumentListResponse],
            options=make_request_options(
                extra_headers=extra_headers,
                extra_query=extra_query,
                extra_body=extra_body,
                timeout=timeout,
                query=maybe_transform(
                    {
                        "assignee": assignee,
                        "end_date": end_date,
                        "limit": limit,
                        "order_by": order_by,
                        "order_dir": order_dir,
                        "scrape_job_id": scrape_job_id,
                        "search": search,
                        "skip": skip,
                        "start_date": start_date,
                        "status": status,
                        "tag_id": tag_id,
                        "type": type,
                    },
                    document_list_params.DocumentListParams,
                ),
            ),
            model=DocumentListResponse,
        )

    async def activate(
        self,
        version_number: int,
        *,
        id: str,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> DocumentActivateResponse:
        """Makes a specific version the active version of a document.

        This is the version
        that will be returned by default when fetching the document.

        Args:
          id: The unique identifier of the document

          version_number: The version number

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not id:
            raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
        return await self._put(
            f"/v0/documents/{id}/versions/{version_number}/activate",
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=DocumentActivateResponse,
        )


class DocumentsResourceWithRawResponse:
    def __init__(self, documents: DocumentsResource) -> None:
        self._documents = documents

        self.create = to_raw_response_wrapper(
            documents.create,
        )
        self.retrieve = to_raw_response_wrapper(
            documents.retrieve,
        )
        self.list = to_raw_response_wrapper(
            documents.list,
        )
        self.activate = to_raw_response_wrapper(
            documents.activate,
        )

    @cached_property
    def versions(self) -> VersionsResourceWithRawResponse:
        return VersionsResourceWithRawResponse(self._documents.versions)

    @cached_property
    def tags(self) -> TagsResourceWithRawResponse:
        return TagsResourceWithRawResponse(self._documents.tags)


class AsyncDocumentsResourceWithRawResponse:
    def __init__(self, documents: AsyncDocumentsResource) -> None:
        self._documents = documents

        self.create = async_to_raw_response_wrapper(
            documents.create,
        )
        self.retrieve = async_to_raw_response_wrapper(
            documents.retrieve,
        )
        self.list = async_to_raw_response_wrapper(
            documents.list,
        )
        self.activate = async_to_raw_response_wrapper(
            documents.activate,
        )

    @cached_property
    def versions(self) -> AsyncVersionsResourceWithRawResponse:
        return AsyncVersionsResourceWithRawResponse(self._documents.versions)

    @cached_property
    def tags(self) -> AsyncTagsResourceWithRawResponse:
        return AsyncTagsResourceWithRawResponse(self._documents.tags)


class DocumentsResourceWithStreamingResponse:
    def __init__(self, documents: DocumentsResource) -> None:
        self._documents = documents

        self.create = to_streamed_response_wrapper(
            documents.create,
        )
        self.retrieve = to_streamed_response_wrapper(
            documents.retrieve,
        )
        self.list = to_streamed_response_wrapper(
            documents.list,
        )
        self.activate = to_streamed_response_wrapper(
            documents.activate,
        )

    @cached_property
    def versions(self) -> VersionsResourceWithStreamingResponse:
        return VersionsResourceWithStreamingResponse(self._documents.versions)

    @cached_property
    def tags(self) -> TagsResourceWithStreamingResponse:
        return TagsResourceWithStreamingResponse(self._documents.tags)


class AsyncDocumentsResourceWithStreamingResponse:
    def __init__(self, documents: AsyncDocumentsResource) -> None:
        self._documents = documents

        self.create = async_to_streamed_response_wrapper(
            documents.create,
        )
        self.retrieve = async_to_streamed_response_wrapper(
            documents.retrieve,
        )
        self.list = async_to_streamed_response_wrapper(
            documents.list,
        )
        self.activate = async_to_streamed_response_wrapper(
            documents.activate,
        )

    @cached_property
    def versions(self) -> AsyncVersionsResourceWithStreamingResponse:
        return AsyncVersionsResourceWithStreamingResponse(self._documents.versions)

    @cached_property
    def tags(self) -> AsyncTagsResourceWithStreamingResponse:
        return AsyncTagsResourceWithStreamingResponse(self._documents.tags)
