/**
 * Utility functions for extracting table of contents from markdown
 */

export interface TableOfContentsItem {
  id: string;
  title: string;
  level: number;
}

/**
 * Generate a URL-friendly ID from a heading text
 */
function slugify(text: string): string {
  return text
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '') // Remove special characters
    .replace(/[\s_-]+/g, '-') // Replace spaces and underscores with hyphens
    .replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens
}

/**
 * Extract headings from markdown content and generate table of contents
 */
export function extractTableOfContents(markdown: string): TableOfContentsItem[] {
  if (!markdown) return [];

  const toc: TableOfContentsItem[] = [];
  const lines = markdown.split('\n');

  for (const line of lines) {
    // Match markdown headings (##, ###, etc.)
    const headingMatch = line.match(/^(#{1,6})\s+(.+)$/);
    if (headingMatch) {
      const level = headingMatch[1].length;
      const title = headingMatch[2].trim();
      
      // Only include h2 and h3 headings in TOC
      if (level >= 2 && level <= 3) {
        const id = slugify(title);
        toc.push({
          id,
          title,
          level,
        });
      }
    }
  }

  return toc;
}


