const FAQ_SECTION_REGEX =
  /^## (?:FAQ|Frequently Asked Questions|Questions fr[ée]quentes)[^\n]*\n([\s\S]*?)(?=^## [^#]|Z)/m;

const QUESTION_BLOCK_REGEX = /^### /m;

/**
 * Extract FAQ question/answer pairs from MDX content.
 * Looks for a ## FAQ section with ### Question? / answer pattern.
 */
export function extractFaqFromContent(
  content: string
): { question: string; answer: string }[] {
  const faqs: { question: string; answer: string }[] = [];

  // Find the FAQ section (## FAQ, ## Frequently Asked Questions, etc.)
  const faqSectionMatch = content.match(FAQ_SECTION_REGEX);

  if (!faqSectionMatch) {
    return faqs;
  }

  const faqContent = faqSectionMatch[1];

  // Split by ### headings (questions)
  const questionBlocks = faqContent.split(QUESTION_BLOCK_REGEX).filter(Boolean);

  for (const block of questionBlocks) {
    const lines = block.trim().split("\n");
    const question = lines[0]?.trim();
    if (!question) {
      continue;
    }

    // Everything after the question heading is the answer
    const answerLines = lines
      .slice(1)
      .filter((line) => line.trim() !== "")
      .map((line) => line.trim());

    if (answerLines.length > 0) {
      faqs.push({
        question,
        answer: answerLines.join(" "),
      });
    }
  }

  return faqs;
}
