"""
Pelican plugin to strip Table of Contents and anchor links from article summaries.

This prevents TOC links and heading anchor links with invalid anchors
from appearing on the homepage.
"""
from pelican import signals
import re


def strip_anchors(text):
    """Jinja2 filter to strip TOC and anchor links from HTML text."""
    if not text:
        return text

    # Remove the entire <div class="contents"> ... </div> block
    text = re.sub(
        r'<div\s+class="contents[^"]*"[^>]*>.*?</div>',
        '',
        text,
        flags=re.DOTALL | re.IGNORECASE
    )

    # Remove anchor links from headings
    # Converts <a class="toc-backref" href="#id1">text</a> to just text
    text = re.sub(
        r'<a[^>]*class="[^"]*toc-backref[^"]*"[^>]*>(.*?)</a>',
        r'\1',
        text,
        flags=re.DOTALL | re.IGNORECASE
    )

    return text


def add_filter(pelican):
    """Add the strip_anchors filter to Jinja2."""
    pelican.env.filters.update({'strip_anchors': strip_anchors})


def register():
    """Register the plugin with Pelican."""
    signals.generator_init.connect(add_filter)
