/**
 * Strip AI reasoning/thinking text from enhanced prompts.
 *
 * Some AI models (GLM, DeepSeek, Llama 3.x with thinking) emit their
 * reasoning process as plain text before the actual answer. This function
 * detects and removes that reasoning, returning only the final prompt.
 *
 * Patterns detected:
 * - Numbered analysis steps (1. ..., 2. ..., etc.)
 * - Self-questioning ("Wait -", "Actually,", "Hmm,", "Let me think")
 * - Markdown code fences (```...```)
 * - Horizontal rules (---) used as separators
 * - Lines that are clearly meta-commentary, not descriptive prompt text
 */

/**
 * Strip reasoning/thinking text from an AI-enhanced prompt, keeping only
 * the actual image generation prompt content.
 */
export function stripReasoning(text: string): string {
  if (!text || typeof text !== 'string') return text;

  let result = text.trim();

  // ── Step 1: Remove <think>...</think> and <thinking>...</thinking> XML blocks ──
  result = result.replace(/<think>[\s\S]*?<\/think>/gi, '');
  result = result.replace(/<thinking>[\s\S]*?<\/thinking>/gi, '');

  // ── Step 2: Remove markdown code fences with analysis content ──
  // If the text starts with a code fence, remove the entire fenced block
  result = result.replace(/^```[\s\S]*?```[\s]*/g, '');

  // ── Step 3: Split into lines and filter out reasoning lines ──
  const lines = result.split('\n');
  const filteredLines: string[] = [];
  let foundPromptStart = false;

  // Patterns that indicate reasoning/meta-commentary, not the actual prompt
  const reasoningPatterns = [
    /^let me\s/i,                    // "Let me analyze", "Let me think", "Let me craft"
    /^wait[\s,-]/i,                  // "Wait -", "Wait,", "Wait."
    /^actually[\s,]/i,              // "Actually,", "Actually."
    /^hmm[\s,.\-]/i,                // "Hmm,", "Hmm."
    /^i (need to|should|think|will|must|can|shall)\s/i, // "I need to", "I think"
    /^sure[,.!?\s]/i,               // "Sure,", "Sure!"
    /^ok[,.!?\s]/i,                  // "Ok,", "Ok!"
    /^now[\s,]/i,                    // "Now,"
    /^\d+\.\s/i,                     // Numbered steps: "1. ", "2. "
    /^step\s*\d+/i,                  // "Step 1", "Step 2"
    /^here('s| is)\s/i,            // "Here's", "Here is"
    /^the (user|client|prompt|request|design)\s/i, // Meta-commentary
    /^this (design|card|image|layout)\s+(should|must|needs|will|can|has)\s/i, // Conditional reasoning
    /^i('ll| will)\s/i,             // "I'll", "I will"
    /^looking at/i,                  // "Looking at this..."
    /^analyzing/i,                   // "Analyzing..."
    /^considering/i,                 // "Considering..."
    /^note:/i,                       // "Note:"
    /^important:/i,                  // "Important:"
    /^first[\s,]/i,                  // "First,", "First "
    /^second[\s,]/i,                 // "Second,"
    /^third[\s,]/i,                  // "Third,"
    /^finally[\s,]/i,               // "Finally,"
    /^however[\s,]/i,               // "However,"
    /^alternatively[\s,]/i,         // "Alternatively,"
    /^instead[\s,]/i,               // "Instead,"
    /^re-?reading/i,                // "Re-reading..."
    /^the instructions? (say|state|require|mention)/i, // Meta-commentary
  ];

  // A line is likely the START of the actual prompt if it begins with
  // descriptive/image-related keywords typical of image generation prompts
  const promptStartPatterns = [
    /^[AT]he\s/i,                    // "A professional...", "The design..."
    /^imagine\s/i,                  // "Imagine a..."
    /^create\s/i,                   // "Create a..."
    /^design\s/i,                   // "Design a..."
    /^produce\s/i,                   // "Produce a..."
    /^generate\s/i,                  // "Generate a..."
    /^a\s+(professional|elegant|premium|sophisticated|modern|minimalist|stunning|beautiful|luxurious|bold|vibrant|clean|formal|corporate|striking|polished|refined)\s/i,
    /^this\s+(is\s+)?(is\s+)?a\s/i,  // "This is a..."
    /^professional/i,                 // "Professional..."
    /^elegant/i,                     // "Elegant..."
    /^sophisticated/i,               // "Sophisticated..."
    /^premium/i,                     // "Premium..."
    /^minimalist/i,                  // "Minimalist..."
    /^stunning/i,                    // "Stunning..."
    /^corporate/i,                   // "Corporate..."
    /^formal/i,                      // "Formal..."
    /^vibrant/i,                     // "Vibrant..."
    /^bold/i,                        // "Bold..."
    /^clean/i,                       // "Clean..."
    /^luxurious/i,                   // "Luxurious..."
    /^refined/i,                     // "Refined..."
    /^polished/i,                    // "Polished..."
    /^striking/i,                    // "Striking..."
    /^modern/i,                      // "Modern..."
  ];

  for (const line of lines) {
    const trimmedLine = line.trim();

    // Skip empty lines before we've found the prompt start
    if (!foundPromptStart && trimmedLine === '') continue;

    // Check if this line matches a prompt start pattern
    if (!foundPromptStart && promptStartPatterns.some(p => p.test(trimmedLine))) {
      foundPromptStart = true;
    }

    // If we haven't found the prompt start yet, check if this line is reasoning
    if (!foundPromptStart) {
      // Skip lines that are clearly reasoning
      if (reasoningPatterns.some(p => p.test(trimmedLine))) continue;

      // Skip short meta lines (less than 40 chars that look like commentary)
      if (trimmedLine.length < 40 && trimmedLine.endsWith(':')) continue;

      // Skip horizontal rules
      if (/^---+/.test(trimmedLine)) continue;

      // Skip lines that are just quotes or brackets
      if (/^["'\[\](){}]/.test(trimmedLine) && trimmedLine.length < 10) continue;

      // If the line doesn't match any reasoning pattern and is long enough,
      // it might be the start of the actual prompt
      if (trimmedLine.length >= 60) {
        foundPromptStart = true;
      }
    }

    // Once we've found the prompt start, include all subsequent lines
    if (foundPromptStart) {
      filteredLines.push(line);
    }
  }

  result = filteredLines.join('\n').trim();

  // ── Step 4: If we ended up with nothing, fall back to the original text ──
  // This handles cases where the AI output was all prompt with no reasoning
  if (!result || result.length < 50) {
    return text.trim();
  }

  // ── Step 5: Remove any trailing reasoning that might appear after the prompt ──
  // Look for lines that start with reasoning indicators after the main content
  const finalLines = result.split('\n');
  let lastPromptLine = finalLines.length;

  for (let i = finalLines.length - 1; i >= 0; i--) {
    const trimmed = finalLines[i].trim();
    if (trimmed === '') continue;
    if (reasoningPatterns.some(p => p.test(trimmed))) {
      lastPromptLine = i;
    } else {
      break;
    }
  }

  if (lastPromptLine < finalLines.length) {
    result = finalLines.slice(0, lastPromptLine).join('\n').trim();
  }

  return result;
}