/**
 * Utility for cleaning AI responses from various formats
 */

/**
 * Remove markdown code blocks from AI responses
 * Handles ```json, ```, and other code block formats
 * @param response The raw response from AI provider
 * @returns Cleaned response without code block markers
 */
export function cleanMarkdownCodeBlocks(response: string): string {
  let cleanResponse = response.trim();
  
  // Check if response is wrapped in ```json ... ``` or ``` ... ``` or ```lang ... ```
  const codeBlockMatch = cleanResponse.match(/^```(?:\w+)?\s*([\s\S]*?)\s*```$/);
  if (codeBlockMatch && codeBlockMatch[1]) {
    return codeBlockMatch[1].trim();
  }
  
  // Alternative: Remove line-by-line if not captured by regex
  if (cleanResponse.startsWith("```")) {
    cleanResponse = cleanResponse.replace(/^```(?:\w+)?\s*\n?/, "");
    if (cleanResponse.endsWith("```")) {
      cleanResponse = cleanResponse.replace(/\n?```\s*$/, "");
    }
  }
  
  return cleanResponse.trim();
}

/**
 * Try to parse a response as JSON, with automatic code block cleaning
 * @param response The raw response from AI provider
 * @returns Parsed JSON object or null if parsing fails
 */
export function parseJsonResponse<T = any>(response: string): T | null {
  try {
    const cleaned = cleanMarkdownCodeBlocks(response);
    return JSON.parse(cleaned) as T;
  } catch {
    return null;
  }
}

/**
 * Extract JSON from mixed text response
 * Useful when AI returns explanation text along with JSON
 * 
 * Note: This uses a greedy regex and is a best-effort attempt. It may not extract 
 * the intended JSON from highly complex or ambiguous text with multiple JSON blocks.
 * 
 * @param response The raw response that may contain JSON somewhere
 * @returns Extracted and parsed JSON or null
 */
export function extractJsonFromText<T = any>(response: string): T | null {
  // First try the simple parse
  const directParse = parseJsonResponse<T>(response);
  if (directParse) return directParse;
  
  // Try to find JSON in the text (looking for { ... } or [ ... ])
  // Note: This greedy regex will capture the largest matching block
  const jsonMatch = response.match(/(\{[\s\S]*\}|\[[\s\S]*\])/);
  if (jsonMatch && jsonMatch[1]) {
    try {
      return JSON.parse(jsonMatch[1]) as T;
    } catch {
      // Continue to next attempt
    }
  }
  
  return null;
}