// GENERATED by tools/gen — DO NOT EDIT.

///|
/// Transport-independent client. Sharing a runtime Client also shares its retry budget.
pub struct Gemini {
  priv client : @client.Client
  priv auth : Auth
  priv base_url : String
  priv server_urls : Map[String, String]
}

///|
pub extend Gemini with @debug.Debug::{to_repr}

///|
pub impl @debug.Debug for Gemini with fn to_repr(_) {
  @debug.Repr::literal("")
}

///|
/// Constructs a client using the caller's backend and clock. Retries are conservative
/// unless configured in the ledger. No per-attempt timeout is set by default. No total timeout is set by default.
/// Backend SendOptions enforce attempts; a supplied timer also bounds runtime waits.
/// Query credentials appear in redirect history and observer URLs.
/// server_urls maps spec server URLs to replacement URLs, independently of base_url.
pub fn Gemini::new(
  backend : &@http.Backend,
  clock : &@rt.Clock,
  auth~ : Auth = Auth::Anonymous,
  base_url~ : String = "https://generativelanguage.googleapis.com",
  server_urls~ : Map[String, String] = {},
  retry~ : @client.RetryPolicy = default_retry(),
  timer? : &@rt.Timer,
  timeout_ms? : Int32,
  total_timeout_ms? : Int32,
  max_body_bytes? : Int32,
) -> Gemini {
  let default = @client.RedirectConfig::default()
  let credential_headers = default.credential_headers.copy()
  credential_headers.push("x-goog-api-key")
  let client = @client.Client::new(
    backend,
    clock,
    retry~,
    timer?,
    timeout_ms?,
    total_ms?=total_timeout_ms,
    max_body_bytes?,
    redirect={ ..default, credential_headers, },
  )
  Gemini::from_client(client, auth~, base_url~, server_urls~)
}

///|
/// Wraps the caller's Client; its policies and retry budget apply.
/// From mttp_core 0.3.0, SDK credential headers are marked on each request.
/// They are stripped when the host, port or scheme changes, except on a
/// same-host HTTP port 80 to HTTPS port 443 upgrade. HTTPS to HTTP is refused
/// by default.
/// Query credentials appear in redirect history and observer URLs.
pub fn Gemini::from_client(
  client : @client.Client,
  auth~ : Auth = Auth::Anonymous,
  base_url~ : String = "https://generativelanguage.googleapis.com",
  server_urls~ : Map[String, String] = {},
) -> Gemini {
  { client, auth, base_url, server_urls: server_urls.copy(), }
}

///|
fn route_matches(url : String, template : String, base_url : String) -> Bool {
  let path = try {
    let parsed = @http.Url::parse(url)
    if parsed.is_absolute() {
      let base = @http.Url::parse(base_url)
      if !parsed.same_origin(base) {
        return false
      }
      let prefix = base.path.trim_end(chars="/").to_owned()
      if parsed.path == prefix {
        "/"
      } else if parsed.path.has_prefix(prefix + "/") {
        parsed.path[prefix.length():].to_owned()
      } else {
        return false
      }
    } else {
      parsed.path
    }
  } catch {
    _ => return false
  }
  let actual = path.split("/").collect()
  let expected = template.split("/").collect()
  if actual.length() != expected.length() {
    return false
  }
  for i, part in expected {
    if !(part.has_prefix("{") && part.has_suffix("}")) && part != actual[i] {
      return false
    }
  }
  true
}

///|
fn Gemini::operation_base(self : Gemini, server : String) -> String {
  let selected = if server == "" {
    self.base_url
  } else {
    self.server_urls.get(server).unwrap_or(server)
  }
  @http.Url::parse(self.base_url)
  .resolve(@http.Url::parse(selected))
  .to_string() catch {
    _ => selected
  }
}

///|
fn Gemini::prepare(
  self : Gemini,
  original : @http.Request,
  operation : String,
) -> Result[@http.Request, Failure] {
  let (use_auth, server) = self.operation_config(operation)
  let base = self.operation_base(server)
  let mut request = { ..original, url: @http.join_url(base, original.url), }
  // Do not attach credentials to a next-page URL outside the operation's origin.
  let trusted = @http.Url::parse(base).same_origin(
    @http.Url::parse(request.url),
  ) catch {
    _ => false
  }
  let headers = request.headers.remove("authorization").remove("x-goog-api-key")
  request = { ..request, headers, }
  try {
    if use_auth && trusted {
      request = self.authenticate(request)
    }
    request.headers.validate()
  } catch {
    @http.TransportError::TransportError(detail~, ..) =>
      return Result::Err(
        Failure::Validation(operation~, parameter="headers", message=detail),
      )
  }
  // Client defaults merge after preparation, even with anonymous SDK auth.
  let credential_headers = request.attributes
    .get(@http.credential_headers)
    .unwrap_or([])
    .copy()
  for name in ["authorization", "x-goog-api-key"] {
    if !credential_headers.iter().any(existing => existing.to_lower() == name) {
      credential_headers.push(name)
    }
  }

  Result::Ok(
    request
    .attribute(@http.credential_headers, credential_headers)
    .attribute(@client.rate_limit_bucket, "gemini" + ":" + operation)
    .attribute(@client.operation_id, operation),
  )
}

///|
fn response_failure(
  operation : String,
  error : @client.ResponseFailure,
) -> Failure {
  match error {
    @client.ResponseFailure::UnexpectedStatus(head, body~) =>
      Failure::Http({
        operation,
        head,
        body,
        typed: typed_error(operation, head, body),
      })
    _ => Failure::Decode(error)
  }
}

///|
/// Buffers and consumes a response; HTTP failures retain status, headers and body.
pub async fn Gemini::send(
  self : Gemini,
  request : @http.Request,
  operation~ : String = self.infer_operation(request),
) -> Result[@client.Reply[Bytes], Failure] {
  let request = match self.prepare(request, operation) {
    Result::Ok(request) => request
    Result::Err(error) => return Result::Err(error)
  }
  try {
    let reply = self.client.send(
      @client.request(request).response(@client.as_bytes()),
    )
    match reply.body {
      Result::Ok(body) =>
        Result::Ok({
          status: reply.status,
          headers: reply.headers,
          body,
          request: reply.request,
          attributes: reply.attributes,
        })
      Result::Err(error) => Result::Err(response_failure(operation, error))
    }
  } catch {
    @http.TransportError::TransportError(..) as error =>
      Result::Err(Failure::Transport(error))
    error => raise error
  }
}

///|
/// Sends the request and applies the matching generated decoder to a consumed body.
pub async fn[T] Gemini::call(
  self : Gemini,
  request : @http.Request,
  decode : (@http.ResponseHead, Bytes) -> Result[T, @client.ResponseFailure],
  operation~ : String = self.infer_operation(request),
) -> Result[T, Failure] {
  match self.send(request, operation~) {
    Result::Err(error) => Result::Err(error)
    Result::Ok(reply) =>
      match
        decode({ status: reply.status, headers: reply.headers, }, reply.body) {
        Result::Ok(value) => Result::Ok(value)
        Result::Err(error) => Result::Err(Failure::Decode(error))
      }
  }
}

///|
/// Consumes SSE events; stop finishes at a protocol sentinel and closes the body.
/// Callback errors propagate. Streaming bodies are never replayed after consumption.
pub async fn Gemini::stream(
  self : Gemini,
  request : @http.Request,
  receive : async (@sse.SseEvent) -> Unit,
  stop? : (@sse.SseEvent) -> Bool,
  operation~ : String = self.infer_operation(request),
) -> Result[Unit, Failure] {
  self.stream_with_head(
    request,
    receive,
    stop=(_, event) => {
      match stop {
        Option::Some(predicate) => predicate(event)
        Option::None => false
      }
    },
    operation~,
  )
}

///|
priv suberror CallbackTransport {
  CallbackTransport(@http.TransportError)
}

///|
async fn Gemini::stream_with_head(
  self : Gemini,
  request : @http.Request,
  receive : async (@sse.SseEvent) -> Unit,
  stop~ : (@http.ResponseHead, @sse.SseEvent) -> Bool,
  operation~ : String,
) -> Result[Unit, Failure] {
  let request = match self.prepare(request, operation) {
    Result::Ok(request) => request
    Result::Err(error) => return Result::Err(error)
  }
  let reader = @client.from_head(head => {
    @client.as_sse(
      event => {
        receive(event) catch {
          @http.TransportError::TransportError(..) as error =>
            raise CallbackTransport(error)
          error => raise error
        }
      },
      stop=event => stop(head, event),
    )
  })
  try {
    let reply = self.client.send(@client.request(request).response(reader))
    match reply.body {
      Result::Ok(value) => Result::Ok(value)
      Result::Err(error) => Result::Err(response_failure(operation, error))
    }
  } catch {
    CallbackTransport(error) => raise error
    @http.TransportError::TransportError(..) as error =>
      Result::Err(Failure::Transport(error))
    error => raise error
  }
}

///|
/// Credentials selected at construction; Debug deliberately redacts values.
pub(all) enum Auth {
  Anonymous
  ApiKey(String)
  ApiKeyInQuery(String)
  OAuthToken(String)
}

///|
pub extend Auth with @debug.Debug::{to_repr}

///|
pub impl @debug.Debug for Auth with fn to_repr(_) {
  @debug.Repr::literal("")
}

///|
fn Gemini::authenticate(
  self : Gemini,
  request : @http.Request,
) -> @http.Request raise @http.TransportError {
  match self.auth {
    Auth::Anonymous => request
    Auth::ApiKey(value) => request.credential("x-goog-api-key", value)
    Auth::ApiKeyInQuery(value) => request.query("key", value)
    Auth::OAuthToken(value) => {
      @http.Headers::of([("authorization", value)]).validate()
      request.credential("authorization", "Bearer " + value)
    }
  }
}

///|
fn Gemini::operation_config(
  self : Gemini,
  operation : String,
) -> (Bool, String) {
  ignore(self)
  match operation {
    "cached_contents_patch" =>
      (
        match self.auth {
          Auth::ApiKey(_) | Auth::ApiKeyInQuery(_) | Auth::OAuthToken(_) => true
          _ => false
        },
        "",
      )
    "cached_contents_get" =>
      (
        match self.auth {
          Auth::ApiKey(_) | Auth::ApiKeyInQuery(_) | Auth::OAuthToken(_) => true
          _ => false
        },
        "",
      )
    "cached_contents_create" =>
      (
        match self.auth {
          Auth::ApiKey(_) | Auth::ApiKeyInQuery(_) | Auth::OAuthToken(_) => true
          _ => false
        },
        "",
      )
    "cached_contents_list" =>
      (
        match self.auth {
          Auth::ApiKey(_) | Auth::ApiKeyInQuery(_) | Auth::OAuthToken(_) => true
          _ => false
        },
        "",
      )
    "cached_contents_delete" =>
      (
        match self.auth {
          Auth::ApiKey(_) | Auth::ApiKeyInQuery(_) | Auth::OAuthToken(_) => true
          _ => false
        },
        "",
      )
    "files_delete" =>
      (
        match self.auth {
          Auth::ApiKey(_) | Auth::ApiKeyInQuery(_) | Auth::OAuthToken(_) => true
          _ => false
        },
        "",
      )
    "files_list" =>
      (
        match self.auth {
          Auth::ApiKey(_) | Auth::ApiKeyInQuery(_) | Auth::OAuthToken(_) => true
          _ => false
        },
        "",
      )
    "media_upload" =>
      (
        match self.auth {
          Auth::ApiKey(_) | Auth::ApiKeyInQuery(_) | Auth::OAuthToken(_) => true
          _ => false
        },
        "",
      )
    "files_get" =>
      (
        match self.auth {
          Auth::ApiKey(_) | Auth::ApiKeyInQuery(_) | Auth::OAuthToken(_) => true
          _ => false
        },
        "",
      )
    "models_list" =>
      (
        match self.auth {
          Auth::ApiKey(_) | Auth::ApiKeyInQuery(_) | Auth::OAuthToken(_) => true
          _ => false
        },
        "",
      )
    "models_stream_generate_content" =>
      (
        match self.auth {
          Auth::ApiKey(_) | Auth::ApiKeyInQuery(_) | Auth::OAuthToken(_) => true
          _ => false
        },
        "",
      )
    "models_get" =>
      (
        match self.auth {
          Auth::ApiKey(_) | Auth::ApiKeyInQuery(_) | Auth::OAuthToken(_) => true
          _ => false
        },
        "",
      )
    "models_embed_content" =>
      (
        match self.auth {
          Auth::ApiKey(_) | Auth::ApiKeyInQuery(_) | Auth::OAuthToken(_) => true
          _ => false
        },
        "",
      )
    "models_count_tokens" =>
      (
        match self.auth {
          Auth::ApiKey(_) | Auth::ApiKeyInQuery(_) | Auth::OAuthToken(_) => true
          _ => false
        },
        "",
      )
    "models_generate_content" =>
      (
        match self.auth {
          Auth::ApiKey(_) | Auth::ApiKeyInQuery(_) | Auth::OAuthToken(_) => true
          _ => false
        },
        "",
      )
    "models_batch_embed_contents" =>
      (
        match self.auth {
          Auth::ApiKey(_) | Auth::ApiKeyInQuery(_) | Auth::OAuthToken(_) => true
          _ => false
        },
        "",
      )
    _ => (true, "")
  }
}

///|
fn Gemini::infer_operation(self : Gemini, request : @http.Request) -> String {
  if request.meth == @http.Method::parse("PATCH") &&
    resource_route_matches(
      request.url,
      "^/v1beta/(?:cachedContents/[^/]+)$",
      self.operation_base(""),
    ) {
    return "cached_contents_patch"
  }
  if request.meth == @http.Method::parse("GET") &&
    resource_route_matches(
      request.url,
      "^/v1beta/(?:cachedContents/[^/]+)$",
      self.operation_base(""),
    ) {
    return "cached_contents_get"
  }
  if request.meth == @http.Method::parse("POST") &&
    route_matches(
      request.url,
      "/v1beta/cachedContents",
      self.operation_base(""),
    ) {
    return "cached_contents_create"
  }
  if request.meth == @http.Method::parse("GET") &&
    route_matches(
      request.url,
      "/v1beta/cachedContents",
      self.operation_base(""),
    ) {
    return "cached_contents_list"
  }
  if request.meth == @http.Method::parse("DELETE") &&
    resource_route_matches(
      request.url,
      "^/v1beta/(?:cachedContents/[^/]+)$",
      self.operation_base(""),
    ) {
    return "cached_contents_delete"
  }
  if request.meth == @http.Method::parse("DELETE") &&
    resource_route_matches(
      request.url,
      "^/v1beta/(?:files/[^/]+)$",
      self.operation_base(""),
    ) {
    return "files_delete"
  }
  if request.meth == @http.Method::parse("GET") &&
    route_matches(request.url, "/v1beta/files", self.operation_base("")) {
    return "files_list"
  }
  if request.meth == @http.Method::parse("POST") &&
    route_matches(request.url, "/v1beta/files", self.operation_base("")) {
    return "media_upload"
  }
  if request.meth == @http.Method::parse("GET") &&
    resource_route_matches(
      request.url,
      "^/v1beta/(?:files/[^/]+)$",
      self.operation_base(""),
    ) {
    return "files_get"
  }
  if request.meth == @http.Method::parse("GET") &&
    route_matches(request.url, "/v1beta/models", self.operation_base("")) {
    return "models_list"
  }
  if request.meth == @http.Method::parse("POST") &&
    resource_route_matches(
      request.url,
      "^/v1beta/(?:models/[^/]+):streamGenerateContent$",
      self.operation_base(""),
    ) {
    return "models_stream_generate_content"
  }
  if request.meth == @http.Method::parse("GET") &&
    resource_route_matches(
      request.url,
      "^/v1beta/(?:models/[^/]+)$",
      self.operation_base(""),
    ) {
    return "models_get"
  }
  if request.meth == @http.Method::parse("POST") &&
    resource_route_matches(
      request.url,
      "^/v1beta/(?:models/[^/]+):embedContent$",
      self.operation_base(""),
    ) {
    return "models_embed_content"
  }
  if request.meth == @http.Method::parse("POST") &&
    resource_route_matches(
      request.url,
      "^/v1beta/(?:models/[^/]+):countTokens$",
      self.operation_base(""),
    ) {
    return "models_count_tokens"
  }
  if request.meth == @http.Method::parse("POST") &&
    resource_route_matches(
      request.url,
      "^/v1beta/(?:models/[^/]+):generateContent$",
      self.operation_base(""),
    ) {
    return "models_generate_content"
  }
  if request.meth == @http.Method::parse("POST") &&
    resource_route_matches(
      request.url,
      "^/v1beta/(?:models/[^/]+):batchEmbedContents$",
      self.operation_base(""),
    ) {
    return "models_batch_embed_contents"
  }
  ""
}

///|
// Match the complete canonical name, including its collection, so operations
// sharing /{name} retain distinct error/auth/observer metadata on generic calls.
fn resource_route_matches(
  url : String,
  pattern : String,
  base_url : String,
) -> Bool {
  try {
    let parsed = @http.Url::parse(url)
    let path = if parsed.is_absolute() {
      let base = @http.Url::parse(base_url)
      if !parsed.same_origin(base) {
        return false
      }
      let prefix = base.path.trim_end(chars="/").to_owned()
      if parsed.path == prefix {
        "/"
      } else if parsed.path.has_prefix(prefix + "/") {
        parsed.path[prefix.length():].to_owned()
      } else {
        return false
      }
    } else {
      parsed.path
    }
    Regex::Regex(pattern).execute(path) is Option::Some(_)
  } catch {
    _ => false
  }
}