import re
from markdown.extensions import Extension
from markdown.preprocessors import Preprocessor
import markdown as md

class ThinkPreprocessor(Preprocessor):
    def run(self, lines):
        new_lines = []
        in_think_block = False
        think_content = []
        
        for line in lines:
            if line.strip().startswith('<think>'):
                in_think_block = True
                # Extract title if present
                title_match = re.match(r'<think.*?title="(.*?)".*?>', line)
                title = title_match.group(1) if title_match else "Think"
                
                # Add think panel HTML
                new_lines.append('<div class="think-panel">')
                new_lines.append('<div class="think-header">')
                new_lines.append(f'    <span>{title}</span>')
                new_lines.append('    <svg class="think-icon w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">')
                new_lines.append('        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>')
                new_lines.append('    </svg>')
                new_lines.append('</div>')
                new_lines.append('<div class="think-content">')
                continue
            elif line.strip() == '</think>' and in_think_block:
                in_think_block = False
                # Process accumulated think content with markdown
                content = '\n'.join(think_content)
                # Use a new markdown instance to avoid recursive processing
                html_content = md.markdown(content, extensions=['markdown.extensions.fenced_code', 
                                                             'markdown.extensions.tables',
                                                             'markdown.extensions.nl2br'])
                new_lines.append(html_content)
                think_content = []
                new_lines.append('</div>')  # Close think-content
                new_lines.append('</div>')  # Close think-panel
                continue
            
            if in_think_block:
                think_content.append(line)
            else:
                new_lines.append(line)
                
        return new_lines

class ThinkExtension(Extension):
    def extendMarkdown(self, md):
        md.preprocessors.register(ThinkPreprocessor(md), 'think', 175)

def makeExtension(**kwargs):
    return ThinkExtension(**kwargs)
