// Copyright 2022 Luca Casonato. All rights reserved. MIT license.
/**
 * Developer Knowledge API Client for Deno
 * =======================================
 * 
 * The Developer Knowledge API provides access to Google's developer knowledge.
 * 
 * Docs: https://developers.google.com/knowledge
 * Source: https://googleapis.deno.dev/v1/developerknowledge:v1.ts
 */

import { auth, CredentialsClient, GoogleAuth, request } from "/_/base@v1/mod.ts";
export { auth, GoogleAuth };
export type { CredentialsClient };

/**
 * The Developer Knowledge API provides access to Google's developer knowledge.
 */
export class DeveloperKnowledge {
  #client: CredentialsClient | undefined;
  #baseUrl: string;

  constructor(client?: CredentialsClient, baseUrl: string = "https://developerknowledge.googleapis.com/") {
    this.#client = client;
    this.#baseUrl = baseUrl;
  }

  /**
   * Retrieves multiple documents, each with its full Markdown content.
   *
   */
  async documentsBatchGet(opts: DocumentsBatchGetOptions = {}): Promise<BatchGetDocumentsResponse> {
    const url = new URL(`${this.#baseUrl}v1/documents:batchGet`);
    if (opts.names !== undefined) {
      url.searchParams.append("names", String(opts.names));
    }
    if (opts.view !== undefined) {
      url.searchParams.append("view", String(opts.view));
    }
    const data = await request(url.href, {
      client: this.#client,
      method: "GET",
    });
    return data as BatchGetDocumentsResponse;
  }

  /**
   * Retrieves a single document with its full Markdown content.
   *
   * @param name Required. Specifies the name of the document to retrieve. Format: `documents/{uri_without_scheme}` Example: `documents/docs.cloud.google.com/storage/docs/creating-buckets`
   */
  async documentsGet(name: string, opts: DocumentsGetOptions = {}): Promise<Document> {
    const url = new URL(`${this.#baseUrl}v1/${ name }`);
    if (opts.view !== undefined) {
      url.searchParams.append("view", String(opts.view));
    }
    const data = await request(url.href, {
      client: this.#client,
      method: "GET",
    });
    return data as Document;
  }

  /**
   * Searches for developer knowledge across Google's developer documentation.
   * Returns DocumentChunks based on the user's query. There may be many chunks
   * from the same Document. To retrieve full documents, use
   * DeveloperKnowledge.GetDocument or DeveloperKnowledge.BatchGetDocuments with
   * the DocumentChunk.parent returned in the
   * SearchDocumentChunksResponse.results.
   *
   */
  async documentsSearchDocumentChunks(opts: DocumentsSearchDocumentChunksOptions = {}): Promise<SearchDocumentChunksResponse> {
    const url = new URL(`${this.#baseUrl}v1/documents:searchDocumentChunks`);
    if (opts.filter !== undefined) {
      url.searchParams.append("filter", String(opts.filter));
    }
    if (opts.pageSize !== undefined) {
      url.searchParams.append("pageSize", String(opts.pageSize));
    }
    if (opts.pageToken !== undefined) {
      url.searchParams.append("pageToken", String(opts.pageToken));
    }
    if (opts.query !== undefined) {
      url.searchParams.append("query", String(opts.query));
    }
    const data = await request(url.href, {
      client: this.#client,
      method: "GET",
    });
    return data as SearchDocumentChunksResponse;
  }
}

/**
 * Response message for DeveloperKnowledge.BatchGetDocuments.
 */
export interface BatchGetDocumentsResponse {
  /**
   * Contains the documents requested.
   */
  documents?: Document[];
}

/**
 * A Document represents a piece of content from the Developer Knowledge
 * corpus.
 */
export interface Document {
  /**
   * Output only. Contains the full content of the document in Markdown format.
   */
  readonly content?: string;
  /**
   * Output only. Specifies the data source of the document. Example data
   * source: `firebase.google.com`
   */
  readonly dataSource?: string;
  /**
   * Output only. Provides a description of the document.
   */
  readonly description?: string;
  /**
   * Identifier. Contains the resource name of the document. Format:
   * `documents/{uri_without_scheme}` Example:
   * `documents/docs.cloud.google.com/storage/docs/creating-buckets`
   */
  name?: string;
  /**
   * Output only. Provides the title of the document.
   */
  readonly title?: string;
  /**
   * Output only. Represents the timestamp when the content or metadata of the
   * document was last updated.
   */
  readonly updateTime?: Date;
  /**
   * Output only. Provides the URI of the content, such as
   * `docs.cloud.google.com/storage/docs/creating-buckets`.
   */
  readonly uri?: string;
  /**
   * Output only. Specifies the DocumentView of the document.
   */
  readonly view?:  | "DOCUMENT_VIEW_UNSPECIFIED" | "DOCUMENT_VIEW_BASIC" | "DOCUMENT_VIEW_FULL" | "DOCUMENT_VIEW_CONTENT";
}

/**
 * A DocumentChunk represents a piece of content from a Document in the
 * DeveloperKnowledge corpus. To fetch the entire document content, pass the
 * `parent` to DeveloperKnowledge.GetDocument or
 * DeveloperKnowledge.BatchGetDocuments.
 */
export interface DocumentChunk {
  /**
   * Output only. Contains the content of the document chunk.
   */
  readonly content?: string;
  /**
   * Output only. Represents metadata about the Document this chunk is from.
   * The DocumentView of this Document message will be set to
   * `DOCUMENT_VIEW_BASIC`. It is included here for convenience so that clients
   * do not need to call DeveloperKnowledge.GetDocument or
   * DeveloperKnowledge.BatchGetDocuments if they only need the metadata fields.
   * Otherwise, clients should use DeveloperKnowledge.GetDocument or
   * DeveloperKnowledge.BatchGetDocuments to fetch the full document content.
   */
  readonly document?: Document;
  /**
   * Output only. Specifies the ID of this chunk within the document. The chunk
   * ID is unique within a document, but not globally unique across documents.
   * The chunk ID is not stable and may change over time.
   */
  readonly id?: string;
  /**
   * Output only. Contains the resource name of the document this chunk is
   * from. Format: `documents/{uri_without_scheme}` Example:
   * `documents/docs.cloud.google.com/storage/docs/creating-buckets`
   */
  readonly parent?: string;
}

/**
 * Additional options for DeveloperKnowledge#documentsBatchGet.
 */
export interface DocumentsBatchGetOptions {
  /**
   * Required. Specifies the names of the documents to retrieve. A maximum of
   * 20 documents can be retrieved in a batch. The documents are returned in the
   * same order as the `names` in the request. Format:
   * `documents/{uri_without_scheme}` Example:
   * `documents/docs.cloud.google.com/storage/docs/creating-buckets`
   */
  names?: string;
  /**
   * Optional. Specifies the DocumentView of the document. If unspecified,
   * DeveloperKnowledge.BatchGetDocuments defaults to `DOCUMENT_VIEW_CONTENT`.
   */
  view?:  | "DOCUMENT_VIEW_UNSPECIFIED" | "DOCUMENT_VIEW_BASIC" | "DOCUMENT_VIEW_FULL" | "DOCUMENT_VIEW_CONTENT";
}

/**
 * Additional options for DeveloperKnowledge#documentsGet.
 */
export interface DocumentsGetOptions {
  /**
   * Optional. Specifies the DocumentView of the document. If unspecified,
   * DeveloperKnowledge.GetDocument defaults to `DOCUMENT_VIEW_CONTENT`.
   */
  view?:  | "DOCUMENT_VIEW_UNSPECIFIED" | "DOCUMENT_VIEW_BASIC" | "DOCUMENT_VIEW_FULL" | "DOCUMENT_VIEW_CONTENT";
}

/**
 * Additional options for DeveloperKnowledge#documentsSearchDocumentChunks.
 */
export interface DocumentsSearchDocumentChunksOptions {
  /**
   * Optional. Applies a strict filter to the search results. The expression
   * supports a subset of the syntax described at https://google.aip.dev/160.
   * While `SearchDocumentChunks` returns DocumentChunks, the filter is applied
   * to `DocumentChunk.document` fields. Supported fields for filtering: *
   * `data_source` (STRING): The source of the document, e.g.
   * `docs.cloud.google.com`. See
   * https://developers.google.com/knowledge/reference/corpus-reference for the
   * complete list of data sources in the corpus. * `update_time` (TIMESTAMP):
   * The timestamp of when the document was last meaningfully updated. A
   * meaningful update is one that changes document's markdown content or
   * metadata. * `uri` (STRING): The document URI, e.g.
   * `https://docs.cloud.google.com/bigquery/docs/tables`. STRING fields support
   * `=` (equals) and `!=` (not equals) operators for **exact match** on the
   * whole string. Partial match, prefix match, and regexp match are not
   * supported. TIMESTAMP fields support `=`, `<`, `<=`, `>`, and `>=`
   * operators. Timestamps must be in RFC-3339 format, e.g.,
   * `"2025-01-01T00:00:00Z"`. You can combine expressions using `AND`, `OR`,
   * and `NOT` (or `-`) logical operators. `OR` has higher precedence than
   * `AND`. Use parentheses for explicit precedence grouping. Examples: *
   * `data_source = "docs.cloud.google.com" OR data_source =
   * "firebase.google.com"` * `data_source != "firebase.google.com"` *
   * `update_time < "2024-01-01T00:00:00Z"` * `update_time >=
   * "2025-01-22T00:00:00Z" AND (data_source = "developer.chrome.com" OR
   * data_source = "web.dev")` * `uri =
   * "https://docs.cloud.google.com/release-notes"` The `filter` string must not
   * exceed 500 characters; values longer than 500 characters will result in an
   * `INVALID_ARGUMENT` error.
   */
  filter?: string;
  /**
   * Optional. Specifies the maximum number of results to return. The service
   * may return fewer than this value. If unspecified, at most 5 results will be
   * returned. The maximum value is 20; values above 20 will result in an
   * INVALID_ARGUMENT error.
   */
  pageSize?: number;
  /**
   * Optional. Contains a page token, received from a previous
   * `SearchDocumentChunks` call. Provide this to retrieve the subsequent page.
   */
  pageToken?: string;
  /**
   * Required. Provides the raw query string provided by the user, such as "How
   * to create a Cloud Storage bucket?".
   */
  query?: string;
}

/**
 * Response message for DeveloperKnowledge.SearchDocumentChunks.
 */
export interface SearchDocumentChunksResponse {
  /**
   * Optional. Provides a token that can be sent as `page_token` to retrieve
   * the next page. If this field is omitted, there are no subsequent pages.
   */
  nextPageToken?: string;
  /**
   * Contains the search results for the given query. Each DocumentChunk in
   * this list contains a snippet of content relevant to the search query. Use
   * the DocumentChunk.parent field of each result with
   * DeveloperKnowledge.GetDocument or DeveloperKnowledge.BatchGetDocuments to
   * retrieve the full document content.
   */
  results?: DocumentChunk[];
}