/** @module
  @summary Finds which web-search providers are usable right now and returns
  their tools.

  Client-side web search needs an API key, and which providers a user has
  keys for varies. Agents ask for whatever is available instead of hardcoding
  one provider, so an agent still runs with no keys at all, just without web
  search. Adding a provider means appending one entry to the catalog here,
  and every agent picks it up.
*/
import { env } from "std::system"
import { search as braveSearch, tavilySearch } from "std::web/search"

type SearchProvider = {
  name: string;
  envKey: string;
  tool: any
}

static const providers: SearchProvider[] = [
  {
  name: "Tavily",
  envKey: "TAVILY_API_KEY",
  tool: tavilySearch.rename("web_search_tavily")
},
  {
  name: "Brave",
  envKey: "BRAVE_API_KEY",
  tool: braveSearch.rename("web_search_brave")
},
]

def hasKey(provider: SearchProvider): boolean {
  const key = env(provider.envKey)
  return key != null && key != ""
}

export def searchTools(): any[] {
  """
  Return the web-search tools whose API key is set, or an empty array when
  no search provider is configured.
  """
  const available = filter(providers, hasKey)
  return map(available, \provider -> provider.tool)
}

static const HOSTED_WEB_SEARCH = "web_search"

export def hostedSearchTools(model: string = ""): string[] {
  """
  Return the provider-hosted search capabilities to request.

  @param model - The model that will run the call, or "" for the branch default
  """
  return [HOSTED_WEB_SEARCH]
}

export def searchProviderNames(): string[] {
  """
  Return the names of the web-search providers whose API key is set, for
  telling a user which search is active.
  """
  const available = filter(providers, hasKey)
  return map(available, \provider -> provider.name)
}
