#!/usr/bin/env node

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { extractWebContent } from './web-extractor.js';
import { searchEndpoint } from './search-tool.js';
import { getCurrentDateTime } from './datetime-tool.js';

// Create MCP server
const server = new McpServer({
  name: "MultiTool",
  version: "0.2.0"
});

// Register the extract_content tool
server.tool(
  "extract_content",
  {
    url: z.string().url("Must provide a valid URL")
  },
  async ({ url }) => {
    try {
      const content = await extractWebContent(url);
      return {
        content: [{ type: "text", text: content }]
      };
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      return {
        content: [{ type: "text", text: `Error extracting content: ${errorMessage}` }],
        isError: true
      };
    }
  }
);

// Register the search tool
server.tool(
  "search",
  {
    query: z.string().describe("The search query to send to the localhost:420/search endpoint")
  },
  async ({ query }) => {
    try {
      const searchResults = await searchEndpoint(query);
      return {
        content: [{ type: "text", text: searchResults }]
      };
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      return {
        content: [{ type: "text", text: `Error performing search: ${errorMessage}` }],
        isError: true
      };
    }
  }
);

// Register the datetime tool
server.tool(
  "get_datetime",
  {
    // No parameters needed for this tool
  },
  async () => {
    try {
      const datetime = getCurrentDateTime();
      return {
        content: [{ type: "text", text: datetime }]
      };
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      return {
        content: [{ type: "text", text: `Error getting datetime: ${errorMessage}` }],
        isError: true
      };
    }
  }
);

// Start the server with stdio transport
async function main() {
  const transport = new StdioServerTransport();
  
  console.error("MultiTool MCP Server starting...");
  
  try {
    await server.connect(transport);
    console.error("MultiTool MCP Server running");
  } catch (error) {
    console.error("Failed to start server:", error);
    process.exit(1);
  }
}

main();