import { getMcpUrl } from '../config';

class McpHttpService {
  private sessionId: string | null = null;

  async callTool(name: string, args: Record<string, unknown>): Promise<{ text: string; isError?: boolean }> {
    const baseUrl = getMcpUrl();
    if (!baseUrl) {
      throw new Error('MCP HTTP service not configured (set MCP_URL env var)');
    }

    const url = `${baseUrl}/mcp`;

    if (!this.sessionId) {
      const initRes = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          jsonrpc: '2.0',
          id: 1,
          method: 'initialize',
          params: {
            protocolVersion: '2025-03-26',
            capabilities: {},
            clientInfo: { name: 'quibot-backend', version: '1.0.0' },
          },
        }),
      });
      const initData = await initRes.json();
      this.sessionId = String(initData.sessionId || initData.result?.sessionId);

      await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          jsonrpc: '2.0',
          id: 2,
          method: 'notifications/initialized',
        }),
        ...(this.sessionId && { headers: { 'Mcp-SessionId': this.sessionId } }),
      });
    }

    const res = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(this.sessionId && { 'Mcp-SessionId': this.sessionId }),
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: Date.now(),
        method: 'tools/call',
        params: { name, arguments: args },
      }),
    });

    const data = await res.json();
    if (data.error) {
      return { text: JSON.stringify(data.error), isError: true };
    }
    const content = data.result?.content?.[0];
    if (!content?.text) {
      throw new Error('MCP tool returned no content');
    }
    return { text: content.text };
  }

  async shutdown(): Promise<void> {
    this.sessionId = null;
  }
}

export const mcpHttpService = new McpHttpService();
