/*
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package genai.tools;

// [START googlegenaisdk_tools_urlcontext_with_txt]

import com.google.genai.Client;
import com.google.genai.types.Candidate;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Tool;
import com.google.genai.types.UrlContext;

public class ToolsUrlContextWithTxt {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash";
    String url1 = "https://cloud.google.com/vertex-ai/generative-ai/docs";
    String url2 = "https://cloud.google.com/docs/overview";
    generateContent(modelId, url1, url2);
  }

  // Generates text with the Url Context Tool.
  public static String generateContent(String modelId, String url1, String url2) {
    // Client Initialization. Once created, it can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      String prompt =
          String.format("Compare the content, purpose, and audiences of %s and %s", url1, url2);

      // Set the Url Context Tool.
      Tool tool = Tool.builder().urlContext(UrlContext.builder().build()).build();

      GenerateContentResponse response =
          client.models.generateContent(
              modelId,
              prompt,
              GenerateContentConfig.builder().tools(tool).responseModalities("TEXT").build());

      // Get response candidate.
      Candidate candidate =
          response
              .candidates()
              .flatMap(candidates -> candidates.stream().findFirst())
              .orElseThrow(
                  () ->
                      new IllegalStateException(
                          "No response candidate was generated by the model."));

      // Print parts of the response.
      candidate
          .content()
          .flatMap(Content::parts)
          .ifPresent(parts -> parts.forEach(part -> part.text().ifPresent(System.out::println)));
      // Example response:
      // The two Google Cloud documentation pages serve distinct purposes and cater to different
      // audiences within the broader Google Cloud ecosystem

      candidate.urlContextMetadata().ifPresent(System.out::println);
      // Example response:
      // UrlContextMetadata{urlMetadata=Optional[[UrlMetadata{
      // retrievedUrl=Optional[https://cloud.google.com/vertex-ai/generative-ai/docs],
      // urlRetrievalStatus=Optional[URL_RETRIEVAL_STATUS_SUCCESS]},
      // UrlMetadata{retrievedUrl=Optional[https://cloud.google.com/docs/overview],
      // urlRetrievalStatus=Optional[URL_RETRIEVAL_STATUS_SUCCESS]}]]}
      return response.text();
    }
  }
}
// [END googlegenaisdk_tools_urlcontext_with_txt]
