/**
 * Description Validation Prompts
 */

function sanitizeIssue(issue) {
  if (!issue || typeof issue !== 'string') return '';
  return issue
    .replace(/\\+$/, '')
    .replace(/\\",?\)?$/, '')
    .replace(/\\\\"/g, '"')
    .replace(/\\"/g, '"')
    .replace(/[,\s]+$/, '')
    .trim();
}

export function buildDescriptionUserPrompt(product, prompts) {
  const parts = [];

  if (prompts.general) {
    parts.push(prompts.general);
    parts.push('');
  }

  if (prompts.companySpecific) {
    parts.push(`COMPANY-SPECIFIC RULES FOR ${product.company_name || 'THIS COMPANY'}:`);
    parts.push(prompts.companySpecific);
    parts.push('');
  }

  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)'}"`);

  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');
}

export function parseDescriptionResponse(parsed, content) {
  if (parsed && typeof parsed.isValid === 'boolean') {
    const rawIssues = Array.isArray(parsed.issues) ? parsed.issues : [];
    const issues = rawIssues.map(sanitizeIssue).filter((issue) => issue.length > 0);
    const suggestion = parsed.suggestion || null;
    const isValid = parsed.isValid && issues.length === 0 && !suggestion;
    return { isValid, suggestion, issues };
  }

  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';
    const isValid = rawIsValid && issues.length === 0 && !suggestion;
    return { isValid, suggestion, issues };
  }

  try {
    const isValidMatch = content.match(/"isValid"\s*:\s*(true|false)/i);
    const isValid = isValidMatch ? isValidMatch[1].toLowerCase() === 'true' : true;

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

    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);
      }
    }
    const finalIsValid = isValid && issues.length === 0 && !suggestion;
    return { isValid: finalIsValid, suggestion, issues };
  } catch {
    return { isValid: true, suggestion: null, issues: [] };
  }
}
