/**
 * Description Validation Prompts
 *
 * Functions for building and parsing description validation prompts.
 * System and general prompts are loaded from the database.
 */

/**
 * Sanitize an issue string from AI response
 * AI sometimes returns malformed strings with escape sequences
 *
 * @param {string} issue - Raw issue string
 * @returns {string} Cleaned issue string
 */
function sanitizeIssue(issue) {
  if (!issue || typeof issue !== 'string') return '';

  let cleaned = issue
    // Remove trailing backslashes (incomplete escapes)
    .replace(/\\+$/, '')
    // Fix malformed escaped quotes at end of string
    .replace(/\\",?\)?$/, '')
    // Clean up double-escaped quotes
    .replace(/\\\\"/g, '"')
    // Clean up single escaped quotes that aren't needed
    .replace(/\\"/g, '"')
    // Remove any remaining trailing punctuation artifacts
    .replace(/[,\s]+$/, '')
    // Trim whitespace
    .trim();

  return cleaned;
}

/**
 * Build the user prompt for description validation
 * Combines database prompts with product data
 *
 * @param {Object} product - Product data
 * @param {string} product.name - Product name
 * @param {string} product.description - Current description
 * @param {string} [product.company_name] - Company name
 * @param {string} [product.categories] - Product categories
 * @param {Object} prompts - Prompts loaded from database
 * @param {string} prompts.general - General description guidelines
 * @param {string} [prompts.companySpecific] - Company-specific rules
 * @returns {string} Complete user prompt
 */
function buildDescriptionUserPrompt(product, prompts) {
  const parts = [];

  // Add general prompt/guidelines if provided
  if (prompts.general) {
    parts.push(prompts.general);
    parts.push(''); // Empty line for separation
  }

  // Add company-specific rules if provided
  if (prompts.companySpecific) {
    parts.push(`COMPANY-SPECIFIC RULES FOR ${product.company_name || 'THIS COMPANY'}:`);
    parts.push(prompts.companySpecific);
    parts.push(''); // Empty line for separation
  }

  // Add product information
  parts.push('PRODUCT TO VALIDATE:');
  parts.push(`NAME: "${product.name || ''}"`);
  parts.push(`COMPANY: ${product.company_name || 'Unknown'}`);

  if (product.categories) {
    parts.push(`CATEGORIES: ${product.categories}`);
  }

  parts.push('');
  parts.push('CURRENT DESCRIPTION:');
  parts.push(`"${product.description || '(empty)'}"`);

  // Add response format instructions
  parts.push('');
  parts.push('CRITICAL RULES:');
  parts.push('- If isValid is false, you MUST provide a suggestion with the improved description');
  parts.push('- If there are ANY issues, isValid MUST be false and suggestion MUST contain the corrected text');
  parts.push('- Only set isValid to true if there are ZERO issues and the description needs no changes');
  parts.push('');
  parts.push('RESPOND WITH JSON:');
  parts.push(JSON.stringify({
    isValid: 'true if perfect, false if ANY changes needed',
    suggestion: 'REQUIRED when isValid is false - the complete improved description',
    issues: ['list each problem found (empty array only if isValid is true)']
  }, null, 2));

  return parts.join('\n');
}

/**
 * Parse the AI response for description validation
 *
 * @param {Object|null} parsed - Parsed JSON from AI
 * @param {string} content - Raw response content
 * @returns {Object}
 */
function parseDescriptionResponse(parsed, content) {
  // If we got valid parsed JSON, use it
  if (parsed && typeof parsed.isValid === 'boolean') {
    // Sanitize issues - AI sometimes returns malformed escape sequences
    const rawIssues = Array.isArray(parsed.issues) ? parsed.issues : [];
    const issues = rawIssues
      .map(sanitizeIssue)
      .filter(issue => issue.length > 0);

    const suggestion = parsed.suggestion || null;

    // IMPORTANT: LLMs sometimes return contradictory data (isValid: true with issues).
    // If there are issues, treat as invalid regardless of what the AI said.
    // Also if there's a suggestion, the AI thought something needed to change.
    const isValid = parsed.isValid && issues.length === 0 && !suggestion;

    return { isValid, suggestion, issues };
  }

  // Handle case where isValid is a string "true"/"false" instead of boolean
  if (parsed && typeof parsed.isValid === 'string') {
    const rawIssues = Array.isArray(parsed.issues) ? parsed.issues : [];
    const issues = rawIssues
      .map(sanitizeIssue)
      .filter(issue => issue.length > 0);
    const suggestion = parsed.suggestion || null;
    const rawIsValid = parsed.isValid.toLowerCase() !== 'false';

    // Same defensive logic: if there are issues, it's not valid
    const isValid = rawIsValid && issues.length === 0 && !suggestion;

    return { isValid, suggestion, issues };
  }

  // Try to extract from content if parsing failed
  try {
    // Look for isValid pattern
    const isValidMatch = content.match(/"isValid"\s*:\s*(true|false)/i);
    const isValid = isValidMatch ? isValidMatch[1].toLowerCase() === 'true' : true;

    // Look for suggestion (might be multiline)
    const suggestionMatch = content.match(/"suggestion"\s*:\s*"((?:[^"\\]|\\.)*)"/s);
    let suggestion = suggestionMatch ? suggestionMatch[1] : null;
    if (suggestion) {
      // Unescape common escapes
      suggestion = suggestion.replace(/\\n/g, '\n').replace(/\\"/g, '"');
    }

    // Look for issues array
    const issuesMatch = content.match(/"issues"\s*:\s*\[([\s\S]*?)\]/);
    let issues = [];
    if (issuesMatch) {
      const issuesContent = issuesMatch[1];
      const issueStrings = issuesContent.match(/"([^"]+)"/g);
      if (issueStrings) {
        issues = issueStrings
          .map(s => sanitizeIssue(s.replace(/"/g, '')))
          .filter(issue => issue.length > 0);
      }
    }

    // Same logic: if there are issues, it's not valid
    const finalIsValid = isValid && issues.length === 0 && !suggestion;

    return { isValid: finalIsValid, suggestion, issues };
  } catch {
    // Default to valid if we can't parse anything
    return { isValid: true, suggestion: null, issues: [] };
  }
}

module.exports = {
  buildDescriptionUserPrompt,
  parseDescriptionResponse
};
