// Code generated by oagen. DO NOT EDIT.

use crate::client::Retab;
#[allow(unused_imports)]
use crate::enums::*;
use crate::error::Error;
#[allow(unused_imports)]
use crate::models::*;
#[allow(unused_imports)]
use serde::Serialize;

pub struct ExtractionsApi<'a> {
    pub(crate) client: &'a Retab,
}

#[derive(Debug, Clone, Serialize)]
pub struct ListParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<String>,
    /// Defaults to `10`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<i64>,
    /// Defaults to `desc`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order: Option<ExtractionsOrder>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filename: Option<String>,
    /// Deprecated alias for prefix filename filtering. Regex patterns are rejected.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filename_regex: Option<String>,
    /// Plain-text search over the filename.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filename_contains: Option<String>,
    /// Filter by document type. Can be repeated. Accepted values: bmp, csv, doc, docm, docx, dotm, dotx, eml, gif, heic, heif, htm, html, jpeg, jpg, json, md, mhtml, msg, odp, ods, odt, ots, ott, pdf, png, ppt, pptx, rtf, svg, tif, tiff, tsv, txt, webp, xlam, xls, xlsb, xlsm, xlsx, xltm, xltx, xml, yaml, yml.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub document_type: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<ExtractionsStatus>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_date: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to_date: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<String>,
}

impl Default for ListParams {
    #[allow(deprecated)]
    fn default() -> Self {
        Self {
            before: Default::default(),
            after: Default::default(),
            limit: Some(10),
            order: Some(ExtractionsOrder::Desc),
            filename: Default::default(),
            filename_regex: Default::default(),
            filename_contains: Default::default(),
            document_type: Default::default(),
            status: Default::default(),
            from_date: Default::default(),
            to_date: Default::default(),
            metadata: Default::default(),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct CreateParams {
    /// Request body sent with this call.
    ///
    /// Required.
    #[serde(skip)]
    pub body: ExtractionRequest,
}

impl CreateParams {
    /// Construct a new `CreateParams` with the required fields set.
    ///
    /// Accepts ergonomic input for MimeData-typed fields via
    /// [`Into<MimeData>`](crate::MimeData) — pass a `PathBuf`,
    /// `Vec<u8>`, `&str` URL, or pre-built `MimeData`.
    #[allow(deprecated)]
    pub fn new<D: Into<crate::MimeData>>(
        document: D,
        json_schema: std::collections::HashMap<String, serde_json::Value>,
    ) -> Self {
        Self {
            body: ExtractionRequest {
                document: document.into(),
                json_schema,
                model: Default::default(),
                instructions: Default::default(),
                n_consensus: Default::default(),
                metadata: Default::default(),
                additional_messages: Default::default(),
                bust_cache: Default::default(),
                stream: Default::default(),
                background: Default::default(),
                chunking_keys: Default::default(),
            },
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct CreateStreamParams {
    /// Request body sent with this call.
    ///
    /// Required.
    #[serde(skip)]
    pub body: ExtractionRequest,
}

impl CreateStreamParams {
    /// Construct a new `CreateStreamParams` with the required fields set.
    ///
    /// Accepts ergonomic input for MimeData-typed fields via
    /// [`Into<MimeData>`](crate::MimeData) — pass a `PathBuf`,
    /// `Vec<u8>`, `&str` URL, or pre-built `MimeData`.
    #[allow(deprecated)]
    pub fn new<D: Into<crate::MimeData>>(
        document: D,
        json_schema: std::collections::HashMap<String, serde_json::Value>,
    ) -> Self {
        Self {
            body: ExtractionRequest {
                document: document.into(),
                json_schema,
                model: Default::default(),
                instructions: Default::default(),
                n_consensus: Default::default(),
                metadata: Default::default(),
                additional_messages: Default::default(),
                bust_cache: Default::default(),
                stream: Default::default(),
                background: Default::default(),
                chunking_keys: Default::default(),
            },
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct GetParams {
    /// When false, returns a cheap status-only projection (no output), served from cache for in-flight background runs.
    ///
    /// Defaults to `true`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_output: Option<bool>,
}

impl Default for GetParams {
    #[allow(deprecated)]
    fn default() -> Self {
        Self {
            include_output: Some(true),
        }
    }
}

impl<'a> ExtractionsApi<'a> {
    /// List Extractions
    ///
    /// List and paginate extractions with optional filtering.
    ///
    /// Returns a paginated list of extraction documents matching the filter criteria.
    ///
    /// The `metadata` parameter accepts a JSON string of key-value pairs to filter by.
    pub async fn list(&self, params: ListParams) -> Result<ExtractionList, Error> {
        self.list_with_options(params, None).await
    }

    /// Variant of [`Self::list`] that accepts per-request [`crate::RequestOptions`].
    pub async fn list_with_options(
        &self,
        params: ListParams,
        options: Option<&crate::RequestOptions>,
    ) -> Result<ExtractionList, Error> {
        let path = "/v1/extractions".to_string();
        let method = http::Method::GET;
        self.client
            .request_page(method, &path, &params, "after", options)
            .await
    }

    /// Create Extraction
    ///
    /// Run a structured extraction on a document.
    ///
    /// Extracts structured data from the `document` according to the supplied
    /// `json_schema`, using the requested `model`. Returns the extraction
    /// with its `output`, consensus details, and usage on `201`. When
    /// `stream` is `true`, partial results are streamed back as they are produced.
    pub async fn create(&self, params: CreateParams) -> Result<Extraction, Error> {
        self.create_with_options(params, None).await
    }

    /// Variant of [`Self::create`] that accepts per-request [`crate::RequestOptions`].
    pub async fn create_with_options(
        &self,
        params: CreateParams,
        options: Option<&crate::RequestOptions>,
    ) -> Result<Extraction, Error> {
        let path = "/v1/extractions".to_string();
        let method = http::Method::POST;
        self.client
            .request_with_body_opts(method, &path, &params, Some(&params.body), options)
            .await
    }

    /// Create Extraction Stream
    ///
    /// Run a structured extraction on a document and stream partial results as they are produced.
    pub async fn create_stream(&self, params: CreateStreamParams) -> Result<(), Error> {
        self.create_stream_with_options(params, None).await
    }

    /// Variant of [`Self::create_stream`] that accepts per-request [`crate::RequestOptions`].
    pub async fn create_stream_with_options(
        &self,
        params: CreateStreamParams,
        options: Option<&crate::RequestOptions>,
    ) -> Result<(), Error> {
        let path = "/v1/extractions/stream".to_string();
        let method = http::Method::POST;
        self.client
            .request_with_body_opts_empty(method, &path, &params, Some(&params.body), options)
            .await
    }

    /// Get Extraction
    ///
    /// Retrieve an extraction.
    ///
    /// Returns the extraction identified by `extraction_id`, including its source
    /// file, schema, `output`, and consensus details. Responds with `404` if no
    /// matching extraction exists.
    pub async fn get(&self, extraction_id: &str, params: GetParams) -> Result<Extraction, Error> {
        self.get_with_options(extraction_id, params, None).await
    }

    /// Variant of [`Self::get`] that accepts per-request [`crate::RequestOptions`].
    pub async fn get_with_options(
        &self,
        extraction_id: &str,
        params: GetParams,
        options: Option<&crate::RequestOptions>,
    ) -> Result<Extraction, Error> {
        let extraction_id = crate::client::path_segment(extraction_id);
        let path = format!("/v1/extractions/{extraction_id}");
        let method = http::Method::GET;
        self.client
            .request_with_query_opts(method, &path, &params, options)
            .await
    }

    /// Delete Extraction
    ///
    /// Delete an extraction.
    ///
    /// Permanently deletes the extraction identified by `extraction_id`. Returns
    /// `204` on success, or `404` if no extraction with that id exists.
    pub async fn delete(&self, extraction_id: &str) -> Result<(), Error> {
        self.delete_with_options(extraction_id, None).await
    }

    /// Variant of [`Self::delete`] that accepts per-request [`crate::RequestOptions`].
    pub async fn delete_with_options(
        &self,
        extraction_id: &str,
        options: Option<&crate::RequestOptions>,
    ) -> Result<(), Error> {
        let extraction_id = crate::client::path_segment(extraction_id);
        let path = format!("/v1/extractions/{extraction_id}");
        let method = http::Method::DELETE;
        self.client
            .request_with_query_opts_empty(method, &path, &(), options)
            .await
    }

    /// Cancel Extraction
    pub async fn create_extraction_cancel(&self, extraction_id: &str) -> Result<Extraction, Error> {
        self.create_extraction_cancel_with_options(extraction_id, None)
            .await
    }

    /// Variant of [`Self::create_extraction_cancel`] that accepts per-request [`crate::RequestOptions`].
    pub async fn create_extraction_cancel_with_options(
        &self,
        extraction_id: &str,
        options: Option<&crate::RequestOptions>,
    ) -> Result<Extraction, Error> {
        let extraction_id = crate::client::path_segment(extraction_id);
        let path = format!("/v1/extractions/{extraction_id}/cancel");
        let method = http::Method::POST;
        self.client
            .request_with_query_opts(method, &path, &(), options)
            .await
    }

    /// Get Extraction Sources
    ///
    /// Return the extraction result enriched with per-leaf source provenance.
    ///
    /// Each extracted leaf value is wrapped as {value, source} where source
    /// contains citation content, surrounding context, and a format-specific
    /// anchor (bbox for PDFs, cell ref for spreadsheets, text span for plain text, etc.).
    pub async fn sources(&self, extraction_id: &str) -> Result<SourcesResponse, Error> {
        self.sources_with_options(extraction_id, None).await
    }

    /// Variant of [`Self::sources`] that accepts per-request [`crate::RequestOptions`].
    pub async fn sources_with_options(
        &self,
        extraction_id: &str,
        options: Option<&crate::RequestOptions>,
    ) -> Result<SourcesResponse, Error> {
        let extraction_id = crate::client::path_segment(extraction_id);
        let path = format!("/v1/extractions/{extraction_id}/sources");
        let method = http::Method::GET;
        self.client
            .request_with_query_opts(method, &path, &(), options)
            .await
    }
}
