/**
 * Sanity Check Prompts
 */

export function buildSanityCheckUserPrompt(products, prompts) {
  const productSummaries = products.map((p, index) => ({
    index,
    name: p.name,
    supplier: p.supplier_name || p.supplier,
    company: p.company_name || p.company,
    supplier_no: p.supplier_no,
    msrp: p.msrp,
    cost_each: p.cost_each,
    qty_per_unit: p.qty_per_unit,
    case_qty: p.case_qty,
    tax_cat: p.tax_cat_name || p.tax_cat,
    size_cat: p.size_cat_name || p.size_cat,
    themes: p.theme_names || p.themes,
    categories: p.category_names || p.categories,
    weight: p.weight,
    length: p.length,
    width: p.width,
    height: p.height,
  }));

  const parts = [];
  if (prompts.general) {
    parts.push(prompts.general);
    parts.push('');
  }
  parts.push(`PRODUCTS TO REVIEW (${products.length} items):`);
  parts.push(JSON.stringify(productSummaries, null, 2));

  parts.push('');
  parts.push('RESPOND WITH JSON:');
  parts.push(JSON.stringify({
    issues: [
      {
        productIndex: 0,
        field: 'msrp',
        issue: 'Description of the issue found',
        suggestion: 'Suggested fix or verification (optional)',
      },
    ],
    summary: '2-3 sentences summarizing the overall product quality',
  }, null, 2));

  parts.push('');
  parts.push('If no issues are found, return empty issues array with positive summary.');

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

export function parseSanityCheckResponse(parsed, content) {
  if (parsed && Array.isArray(parsed.issues)) {
    return {
      issues: parsed.issues.map((issue) => ({
        productIndex: issue.productIndex ?? issue.index ?? 0,
        field: issue.field || 'unknown',
        issue: issue.issue || issue.message || '',
        suggestion: issue.suggestion || null,
      })),
      summary: parsed.summary || 'Review complete',
    };
  }

  try {
    const issuesMatch = content.match(/"issues"\s*:\s*\[([\s\S]*?)\]/);
    let issues = [];
    if (issuesMatch) {
      try {
        const arrayContent = `[${issuesMatch[1]}]`;
        const parsedIssues = JSON.parse(arrayContent);
        issues = parsedIssues.map((issue) => ({
          productIndex: issue.productIndex ?? issue.index ?? 0,
          field: issue.field || 'unknown',
          issue: issue.issue || issue.message || '',
          suggestion: issue.suggestion || null,
        }));
      } catch {
        /* fall through */
      }
    }
    const summaryMatch = content.match(/"summary"\s*:\s*"([^"]+)"/);
    const summary = summaryMatch ? summaryMatch[1] : 'Review complete';
    return { issues, summary };
  } catch {
    return { issues: [], summary: 'Could not parse review results' };
  }
}
