// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
//
// SPDX-License-Identifier: GPL-3.0-or-later

import { Type } from "@sinclair/typebox";
import type { AgentTool } from "@mariozechner/pi-agent-core";
import { search } from "kagi-ken";
import { FetchError, ToolInputError } from "../../util/errors.js";

const SearchSchema = Type.Object({
  query: Type.String({ description: "Search query" }),
});

export const createWebSearchTool = (sessionToken: string): AgentTool => ({
  name: "web_search",
  label: "Web Search",
  description: "Search the web. Returns structured results with titles, URLs, and snippets.",
  parameters: SearchSchema as any,
  execute: async (_toolCallId: string, params: any) => {
    if (!sessionToken) {
      throw new ToolInputError("Web search is not configured");
    }

    try {
      const result = await search(params.query, sessionToken);
      return {
        content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
        details: { query: params.query, resultCount: result?.data?.length ?? 0 },
      };
    } catch (error: any) {
      throw new FetchError(
        `kagi:search?q=${encodeURIComponent(params.query)}`,
        error?.message ?? String(error),
      );
    }
  },
});
