interface TOCItem {
  id: string;
  title: string;
}

/**
 * Parse table of contents from HTML content
 * Extracts h2 and h3 headings and generates IDs
 */
export function parseTableOfContents(content: string): TOCItem[] {
  const toc: TOCItem[] = [];
  
  // Match h2 and h3 tags
  const headingRegex = /<h([23])[^>]*>(.*?)<\/h\1>/gi;
  let match;
  
  while ((match = headingRegex.exec(content)) !== null) {
    const level = match[1];
    const title = match[2].replace(/<[^>]*>/g, ''); // Strip HTML tags
    
    // Generate ID from title
    const id = title
      .toLowerCase()
      .replace(/[^\w\s-]/g, '')
      .replace(/\s+/g, '-')
      .replace(/--+/g, '-')
      .trim();
    
    toc.push({ id, title });
  }
  
  return toc;
}

/**
 * Add IDs to headings in HTML content for TOC linking
 */
export function addHeadingIds(content: string): string {
  return content.replace(/<h([23])([^>]*)>(.*?)<\/h\1>/gi, (match, level, attrs, title) => {
    const cleanTitle = title.replace(/<[^>]*>/g, '');
    const id = cleanTitle
      .toLowerCase()
      .replace(/[^\w\s-]/g, '')
      .replace(/\s+/g, '-')
      .replace(/--+/g, '-')
      .trim();
    
    return `<h${level}${attrs} id="${id}">${title}</h${level}>`;
  });
}

/**
 * Parse JSONB field safely
 */
export function parseJsonField<T>(field: unknown): T | null {
  console.log('[parseJsonField] Input:', typeof field, field);
  
  if (!field) {
    console.log('[parseJsonField] Field is falsy, returning null');
    return null;
  }
  
  try {
    if (typeof field === 'string') {
      console.log('[parseJsonField] Parsing string');
      const result = JSON.parse(field) as T;
      console.log('[parseJsonField] Parsed result:', result);
      return result;
    }
    console.log('[parseJsonField] Returning field as-is');
    return field as T;
  } catch (error) {
    console.error('[parseJsonField] Error parsing JSON field:', error);
    return null;
  }
}
