/**
 * Name Validation Prompts
 */

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

export function buildNameUserPrompt(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'}`);
  parts.push(`LINE: ${product.line_name || 'None'}`);
  if (product.subline_name) parts.push(`SUBLINE: ${product.subline_name}`);

  if (product.siblingNames && product.siblingNames.length > 0) {
    parts.push('');
    parts.push(`OTHER PRODUCTS IN THIS LINE (${product.siblingNames.length + 1} total including this one):`);
    product.siblingNames.forEach((name) => parts.push(`- ${name}`));
  }

  parts.push('');
  parts.push('RESPOND WITH JSON:');
  parts.push(JSON.stringify({
    isValid: 'true/false',
    suggestion: 'corrected name if changes needed, or null if valid',
    issues: ['issue 1', 'issue 2 (empty array if valid)'],
  }, null, 2));

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

export function parseNameResponse(parsed, content) {
  console.log('[parseNameResponse] Input:', {
    hasParsed: !!parsed,
    parsedIsValid: parsed?.isValid,
    parsedType: typeof parsed?.isValid,
    contentPreview: content?.substring(0, 3000),
  });

  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;
    console.log('[parseNameResponse] Parsed isValid as string:', parsed.isValid, '→', isValid);
    return { isValid, suggestion, issues };
  }

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

    console.log('[parseNameResponse] Regex extraction:', {
      isValidMatch: isValidMatch?.[0],
      isValidValue: isValidMatch?.[1],
      resultIsValid: isValid,
    });

    const suggestionMatch = content.match(/"suggestion"\s*:\s*(?:"([^"\\]*(?:\\.[^"\\]*)*)"|null)/);
    const suggestion = suggestionMatch ? (suggestionMatch[1] || null) : null;

    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: [] };
  }
}
