import re
from flask_login import current_user

def process_content(content):
    """
    Process reading content by:
    1. Replacing placeholders like [name] with the student's username
    2. Formatting headings, notes, and highlights
    3. Adding data attributes for text-to-speech tracking
    """
    if not content:
        return ""
    
    # Replace placeholders with actual user information
    if current_user and current_user.is_authenticated and hasattr(current_user, 'username'):
        # Replace [name] with the student's username
        content = content.replace('[name]', current_user.username)
        
        # Replace [first_name] with the student's first name if available
        if hasattr(current_user, 'first_name') and current_user.first_name:
            content = content.replace('[first_name]', current_user.first_name)
        else:
            content = content.replace('[first_name]', current_user.username)
    
    # Split content into paragraphs
    paragraphs = content.split('\n\n')
    processed_paragraphs = []
    current_index = 0
    
    for paragraph in paragraphs:
        lines = paragraph.strip().split('\n')
        processed_lines = []
        
        for line in lines:
            line = line.strip()
            if not line:
                continue
                
            # Add data attributes for tracking
            data_attrs = f'data-start="{current_index}" data-end="{current_index + len(line)}"'
            current_index += len(line) + 1  # +1 for space after each line
            
            # Process headings
            if line.startswith('H1:'):
                line = f'<h1 class="text-3xl font-bold mb-4 mt-6" {data_attrs}>{line[3:].strip()}</h1>'
            elif line.startswith('H2:'):
                line = f'<h2 class="text-2xl font-semibold mb-3 mt-5" {data_attrs}>{line[3:].strip()}</h2>'
            # Process notes
            elif line.startswith('Note:'):
                line = f'<div class="note rounded-lg" {data_attrs}>{line}</div>'
            # Process inline highlights
            else:
                line = re.sub(r'\*\*(.*?)\*\*', r'<span class="highlight">\1</span>', line)
                line = f'<p {data_attrs}>{line}</p>'
            
            processed_lines.append(line)
        
        if processed_lines:
            processed_paragraphs.append('\n'.join(processed_lines))
    
    return '\n\n'.join(processed_paragraphs)
