import { _search, _tavilySearch } from "agency-lang/stdlib-lib/search.js"

/** @module
  @summary Search the web with Brave or Tavily.
  Search the web from Agency code, backed by the Brave Search API
  (https://brave.com/search/api/), or use Tavily as an alternative. Configure
  `BRAVE_API_KEY` or `TAVILY_API_KEY` for the provider you use.

  ```ts
  import { search } from "std::web/search"

  node main() {
    const results = search("agency language programming")
    print(results)
  }
  ```
*/

type SearchResult = {
  title: string;
  url: string;
  description: string
}

effect std::search { query: string, count: number, country: string, searchLang: string, safesearch: string, freshness: string }
effect std::tavilySearch { query: string, count: number, searchDepth: string, topic: string }

@capabilities(network)
export def search(
  query: string,
  count: number = 5,
  apiKey: string = "",
  country: string = "",
  searchLang: string = "",
  safesearch: string = "",
  freshness: string = "",
): SearchResult[] raises <std::search> {
  """
  Search the web with Brave.

  @param apiKey - Leave empty to use BRAVE_API_KEY.
  @param country - A two-letter country code to localize results, such as "US".
  @param searchLang - A result language code, such as "en".
  @param safesearch - Use "off", "moderate", or "strict", or empty for the provider default.
  @param freshness - Use "pd", "pw", "pm", or "py" for the past day, week, month, or year.
  """
  return interrupt std::search("Are you sure you want to perform this web search?", {
    query: query,
    count: count,
    country: country,
    searchLang: searchLang,
    safesearch: safesearch,
    freshness: freshness
  })
  return _search(
    query,
    {
    count: count,
    apiKey: apiKey,
    country: country,
    searchLang: searchLang,
    safesearch: safesearch,
    freshness: freshness
  },
  )
}

/** Configure a Tavily API key at https://tavily.com before using this provider. */
@capabilities(network)
export def tavilySearch(
  query: string,
  count: number = 5,
  apiKey: string = "",
  searchDepth: string = "",
  topic: string = "",
): SearchResult[] raises <std::tavilySearch> {
  """
  Search the web with Tavily and return source links with extracted snippets.

  @param apiKey - Leave empty to use TAVILY_API_KEY.
  @param searchDepth - Use "basic" for faster retrieval or "advanced" for deeper retrieval.
  @param topic - Search "general" web content or "news".
  """
  return interrupt std::tavilySearch("Are you sure you want to perform this web search?", {
    query: query,
    count: count,
    searchDepth: searchDepth,
    topic: topic
  })
  return _tavilySearch(
    query,
    {
    count: count,
    apiKey: apiKey,
    searchDepth: searchDepth,
    topic: topic
  },
  )
}
