const TABLE_ROW_PATTERN = /^\|(.+)\|$/;
const SEPARATOR_PATTERN = /^[\s|:-]+$/;

/**
 * Extracts table rows under a given markdown heading as string[][] from raw markdown.
 * Skips header and separator rows. Returns empty array if heading or table not found.
 */
export function parseMarkdownTable(markdown: string, heading: string): string[][] {
  const lines = markdown.split("\n");
  const rows: string[][] = [];
  let inSection = false;
  let headerSkipped = false;

  for (const line of lines) {
    const trimmed = line.trim();

    if (trimmed === heading || trimmed.startsWith(`${heading} `)) {
      inSection = true;
      continue;
    }

    if (!inSection) continue;

    // Stop at next heading
    if (trimmed.startsWith("#")) break;

    if (!trimmed) continue;

    const match = TABLE_ROW_PATTERN.exec(trimmed);
    if (!match) continue;

    const cells = match[1].split("|").map((c) => c.trim());

    // Skip header row
    if (!headerSkipped) {
      headerSkipped = true;
      continue;
    }

    // Skip separator row (e.g. |---|---|)
    if (SEPARATOR_PATTERN.test(match[1])) continue;

    rows.push(cells);
  }

  return rows;
}
