import type { McpServer } from '@prisma/client';

export interface McpConfigServer {
  command?: string;
  args?: string[];
  url?: string;
  headers?: Record<string, string>;
  env?: Record<string, string>;
}

export interface McpConfig {
  mcpServers: Record<string, McpConfigServer>;
}

/**
 * Generate .mcp.json config from servers with their resolved env vars.
 */
export function generateMcpConfig(
  servers: Array<{ server: McpServer; resolvedEnv: Record<string, string> }>,
): McpConfig {
  const mcpServers: Record<string, McpConfigServer> = {};

  for (const { server, resolvedEnv } of servers) {
    if (server.transport === 'SSE' || server.transport === 'STREAMABLE_HTTP') {
      // Point at mcpd proxy URL for non-STDIO transports
      mcpServers[server.name] = {
        url: `http://localhost:3100/api/v1/mcp/proxy/${server.name}`,
      };
    } else {
      // STDIO — npx command approach
      const config: McpConfigServer = {
        command: 'npx',
        args: ['-y', server.packageName ?? server.name],
      };

      if (Object.keys(resolvedEnv).length > 0) {
        config.env = resolvedEnv;
      }

      mcpServers[server.name] = config;
    }
  }

  return { mcpServers };
}
