import type {MarkdownBlock} from './interfaces';

export function parseTableRow(line: string): string[] {
  return line
    .split('|')
    .slice(1, -1)
    .map(cell => cell.trim());
}

export function isTableSeparator(line: string): boolean {
  return /^\|[\s-:|]+\|$/.test(line.trim());
}

export function isTableRow(line: string): boolean {
  const trimmed = line.trim();
  return trimmed.startsWith('|') && trimmed.endsWith('|');
}

export function parseMarkdownBlocks(markdown: string): MarkdownBlock[] {
  const lines = markdown.split('\n');
  const blocks: MarkdownBlock[] = [];
  let orderedIndex = 0;
  let i = 0;

  while (i < lines.length) {
    const trimmed = lines[i].trim();

    if (!trimmed) {
      orderedIndex = 0;
      i++;
      continue;
    }

    if (
      isTableRow(trimmed) &&
      i + 1 < lines.length &&
      isTableSeparator(lines[i + 1])
    ) {
      const headers = parseTableRow(trimmed);
      const rows: string[][] = [];
      i += 2;
      while (i < lines.length && isTableRow(lines[i].trim())) {
        rows.push(parseTableRow(lines[i]));
        i++;
      }
      blocks.push({type: 'table', headers, rows});
      orderedIndex = 0;
      continue;
    }

    if (trimmed === '---') {
      blocks.push({type: 'hr'});
      orderedIndex = 0;
    } else if (trimmed.startsWith('### ')) {
      blocks.push({type: 'h3', text: trimmed.slice(4)});
      orderedIndex = 0;
    } else if (trimmed.startsWith('## ')) {
      blocks.push({type: 'h2', text: trimmed.slice(3)});
      orderedIndex = 0;
    } else if (trimmed.startsWith('# ')) {
      blocks.push({type: 'h1', text: trimmed.slice(2)});
      orderedIndex = 0;
    } else if (trimmed.startsWith('- ')) {
      blocks.push({
        type: 'li',
        text: trimmed.slice(2),
        ordered: false,
        index: 0,
      });
      orderedIndex = 0;
    } else if (/^\d+\.\s/.test(trimmed)) {
      orderedIndex++;
      blocks.push({
        type: 'li',
        text: trimmed.replace(/^\d+\.\s/, ''),
        ordered: true,
        index: orderedIndex,
      });
    } else {
      blocks.push({type: 'paragraph', text: trimmed});
    }
    i++;
  }
  return blocks;
}
