// 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 Tabstack from "@tabstack/sdk";
import { FetchError, ToolInputError } from "../../util/errors.js";

export interface WebFetchResult {
  content: string;
  url: string;
}

const FetchSchema = Type.Object({
  url: Type.String({ description: "URL to fetch" }),
  nocache: Type.Optional(Type.Boolean({ description: "Bypass cache and fetch fresh content" })),
});

export function createWebFetchTool(apiKey: string): AgentTool {
  return {
    name: "web_fetch",
    label: "Web Fetch",
    description: "Fetch a URL and return its content as markdown.",
    parameters: FetchSchema as any,
    execute: async (_toolCallId: string, params: any) => {
      if (!apiKey) {
        throw new ToolInputError("Web fetch is not configured");
      }

      const client = new Tabstack({ apiKey });

      try {
        const result = await client.extract.markdown({
          url: params.url,
          nocache: params.nocache ?? false,
        });

        return {
          content: [{ type: "text", text: result.content ?? "" }],
          details: { url: params.url, length: result.content?.length ?? 0 },
        };
      } catch (error: any) {
        throw new FetchError(params.url, error?.message ?? String(error));
      }
    },
  };
}
