import matter from "gray-matter";

export type Frontmatter = Record<string, unknown>;

export function parseMarkdownWithFrontmatter(source: string) {
  const { content, data } = matter(source);
  const headings = extractHeadings(content);
  return { content, frontmatter: data as Frontmatter, headings };
}

function extractHeadings(content: string) {
  const regex = /^(#{1,6})\s+(.+)$/gm;
  const headings: { id: string; text: string; level: number }[] = [];
  let match: RegExpExecArray | null;
  while ((match = regex.exec(content)) !== null) {
    const level = match[1].length;
    const text = match[2].trim();
    const id = text
      .toLowerCase()
      .replace(/[^a-z0-9\s-]/g, "")
      .replace(/\s+/g, "-");
    headings.push({ id, text, level });
  }
  return headings;
}
