/**
 * Name Validation Prompts
 *
 * Functions for building and parsing name 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 name validation
 * Combines database prompts with product data
 *
 * @param {Object} product - Product data
 * @param {string} product.name - Current product name
 * @param {string} [product.company_name] - Company name
 * @param {string} [product.line_name] - Product line name
 * @param {string} [product.subline_name] - Product subline name
 * @param {string[]} [product.siblingNames] - Names of other products in the same line
 * @param {Object} prompts - Prompts loaded from database
 * @param {string} prompts.general - General naming conventions
 * @param {string} [prompts.companySpecific] - Company-specific rules
 * @returns {string} Complete user prompt
 */
function buildNameUserPrompt(product, prompts) {
  const parts = [];

  // Add general prompt/conventions 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'}`);
  parts.push(`LINE: ${product.line_name || 'None'}`);
  if (product.subline_name) {
    parts.push(`SUBLINE: ${product.subline_name}`);
  }

  // Add sibling context for naming decisions
  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}`);
    });
  }

  // Add response format instructions
  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');
}

/**
 * Parse the AI response for name validation
 *
 * @param {Object|null} parsed - Parsed JSON from AI
 * @param {string} content - Raw response content
 * @returns {Object}
 */
function parseNameResponse(parsed, content) {
  // Debug: Log what we're trying to parse
  console.log('[parseNameResponse] Input:', {
    hasParsed: !!parsed,
    parsedIsValid: parsed?.isValid,
    parsedType: typeof parsed?.isValid,
    contentPreview: content?.substring(0, 3000)
  });

  // 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.
    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;

    console.log('[parseNameResponse] Parsed isValid as string:', parsed.isValid, '→', isValid);
    return { isValid, suggestion, issues };
  }

  // Try to extract from content if parsing failed
  try {
    // Look for isValid pattern - handle both boolean and quoted string
    // Matches: "isValid": true, "isValid": false, "isValid": "true", "isValid": "false"
    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
    });

    // Look for suggestion - handle escaped quotes and null
    const suggestionMatch = content.match(/"suggestion"\s*:\s*(?:"([^"\\]*(?:\\.[^"\\]*)*)"|null)/);
    const suggestion = suggestionMatch ? (suggestionMatch[1] || null) : null;

    // 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 defensive 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 = {
  buildNameUserPrompt,
  parseNameResponse
};
