"""Remove the duplicate cross-references a repeated autolink run left behind.

Keep the first link to each article in each section; unwrap the rest back to
the words they were wrapped around. The author's text is never changed — only
the marker around it.
"""
import re
import sys

from app.database import SessionLocal
from app.models.article import Article
from app.services import article_service

DRY = "--apply" not in sys.argv
MARKER = re.compile(r"\[\[([^\]|]+)\|([a-z0-9-]+)\]\]")

db = SessionLocal()
touched = removed = 0
for article in db.query(Article).filter(Article.deleted_at.is_(None)).all():
    sections = list(article.sections or [])
    changed = False
    for index, section in enumerate(sections):
        body = section.get("content") or ""
        seen: set[str] = set()

        def once(match):
            global removed
            slug = match.group(2)
            if slug in seen:
                removed += 1
                return match.group(1)          # the words, without the link
            seen.add(slug)
            return match.group(0)

        fixed = MARKER.sub(once, body)
        if fixed != body:
            sections[index] = {**section, "content": fixed}
            changed = True
    if changed:
        touched += 1
        if not DRY:
            article_service.snapshot(db, article, None, note="duplicate links removed")
            article.sections = sections
            db.add(article)
if not DRY:
    db.commit()
print(f"{'would remove' if DRY else 'removed'} {removed} duplicate links "
      f"across {touched} articles")
db.close()
