/**
 * MCP Helper Functions
 *
 * Common utilities for MCP HTTP servers including response formatting
 * and error handling.
 */

import { McpToolCallResponse, McpErrorResponse } from './mcp-types.ts';

/**
 * Create a successful MCP tool response
 */
export function createMcpResponse(data: any): McpToolCallResponse {
  return {
    content: [
      {
        type: 'text',
        text: typeof data === 'string' ? data : JSON.stringify(data, null, 2)
      }
    ]
  };
}

/**
 * Create an MCP error response
 */
export function createMcpError(code: string, message: string): McpErrorResponse {
  return {
    error: {
      code,
      message
    },
    isError: true
  };
}

/**
 * Create HTTP Response for MCP error
 */
export function createMcpErrorResponse(code: string, message: string, status: number = 400): Response {
  return new Response(
    JSON.stringify(createMcpError(code, message)),
    {
      status,
      headers: { 'Content-Type': 'application/json' }
    }
  );
}

/**
 * Create HTTP Response for MCP success
 */
export function createMcpSuccessResponse(data: any): Response {
  return new Response(
    JSON.stringify(createMcpResponse(data)),
    {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    }
  );
}

/**
 * Validate required parameters in MCP tool call
 */
export function validateParams(
  args: Record<string, any>,
  required: string[]
): { valid: boolean; missing?: string[] } {
  const missing = required.filter(param => !args[param]);

  if (missing.length > 0) {
    return { valid: false, missing };
  }

  return { valid: true };
}

/**
 * Clean response data by removing URL/href fields and empty values
 * Recursively processes objects and arrays
 */
export function cleanResponseData(data: any): any {
  if (data === null || data === undefined) {
    return undefined;
  }

  // Handle arrays
  if (Array.isArray(data)) {
    return data.map(item => cleanResponseData(item)).filter(item => item !== undefined);
  }

  // Handle objects
  if (typeof data === 'object') {
    const cleaned: Record<string, any> = {};

    for (const [key, value] of Object.entries(data)) {
      // Skip keys containing 'url' or 'href' (case-insensitive)
      if (key.toLowerCase().includes('url') || key.toLowerCase().includes('href')) {
        continue;
      }

      // Clean the value recursively
      const cleanedValue = cleanResponseData(value);

      // Skip empty values (null, undefined, empty string, empty array, empty object)
      if (cleanedValue === null || cleanedValue === undefined || cleanedValue === '') {
        continue;
      }

      if (Array.isArray(cleanedValue) && cleanedValue.length === 0) {
        continue;
      }

      if (typeof cleanedValue === 'object' && !Array.isArray(cleanedValue) && Object.keys(cleanedValue).length === 0) {
        continue;
      }

      cleaned[key] = cleanedValue;
    }

    return Object.keys(cleaned).length > 0 ? cleaned : undefined;
  }

  // Return primitive values as-is
  return data;
}
