import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
import { loadWebSearchConfig } from "./src/config.ts";
import { createExaProvider } from "./src/providers/exa.ts";
import type { WebProvider } from "./src/providers/types.ts";
import { createWebSearchTool } from "./src/tools/web-search.ts";

async function resolveProvider(providerName?: string): Promise<WebProvider> {
  const config = await loadWebSearchConfig();
  const selectedName = providerName ?? config.defaultProviderName;
  const providerConfig = config.providersByName.get(selectedName);

  if (!providerConfig) {
    throw new Error(
      `Unknown web-search provider \"${selectedName}\". Configured providers: ${[...config.providersByName.keys()].join(", ")}`,
    );
  }

  switch (providerConfig.type) {
    case "exa":
      return createExaProvider(providerConfig);
    default:
      throw new Error(`Unsupported web-search provider type: ${(providerConfig as { type: string }).type}`);
  }
}

export default function webSearch(pi: ExtensionAPI) {
  pi.registerTool(createWebSearchTool({ resolveProvider }));
}
