#!/usr/bin/env node
/**
 * Reonomy MCP Server
 *
 * Bridges Claude (via MCP protocol) to the Reonomy Express API.
 * Exposes search, scrape, results, filters, and export tools.
 * Serves MCP App resources (search, results, dashboard UIs).
 *
 * Run: npx tsx src/mcp/server.ts
 * Config env: REONOMY_API_URL (default http://localhost:3847)
 */

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { tools } from "./tools.js";
import { resources, readResource } from "./resources.js";
import { zodToJsonSchema } from "./zod-to-json.js";

// ─── Server Setup ───────────────────────────────────────────────

const server = new McpServer({
  name: "reonomy",
  version: "1.0.0",
});

// ─── Register Tools ─────────────────────────────────────────────

for (const tool of tools) {
  const jsonSchema = zodToJsonSchema(tool.inputSchema);

  server.tool(
    tool.name,
    tool.description,
    jsonSchema,
    async (args: Record<string, unknown>) => {
      try {
        const result = await tool.handler(args);
        return {
          content: result.content,
          _meta: result._meta,
        };
      } catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        return {
          content: [{ type: "text" as const, text: `Error: ${message}` }],
          isError: true,
        };
      }
    }
  );
}

// ─── Register Resources ─────────────────────────────────────────

for (const resource of resources) {
  server.resource(
    resource.name,
    resource.uri,
    { description: resource.description, mimeType: resource.mimeType },
    async () => {
      const data = readResource(resource.uri);
      if (!data) {
        return {
          contents: [
            {
              uri: resource.uri,
              mimeType: "text/plain",
              text: `Resource not found: ${resource.uri}`,
            },
          ],
        };
      }
      return {
        contents: [
          {
            uri: data.uri,
            mimeType: data.mimeType,
            text: data.text,
          },
        ],
      };
    }
  );
}

// ─── Start Server ───────────────────────────────────────────────

async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("[reonomy-mcp] Server started on stdio");
  console.error(`[reonomy-mcp] API target: ${process.env.REONOMY_API_URL || "http://localhost:3847"}`);
  console.error(`[reonomy-mcp] Tools: ${tools.map((t) => t.name).join(", ")}`);
  console.error(`[reonomy-mcp] Resources: ${resources.map((r) => r.uri).join(", ")}`);
}

main().catch((err) => {
  console.error("[reonomy-mcp] Fatal error:", err);
  process.exit(1);
});
