"""Link the first mention of every article title, across the whole bank."""
import sys

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

DRY = "--apply" not in sys.argv

db = SessionLocal()
rows = db.query(Article).filter(Article.deleted_at.is_(None)).all()
matchers = autolink.index([(a.title, a.slug) for a in rows
                           if (a.status or "") == "published"])
print(f"{len(rows)} articles, {len(matchers)} title forms to match")

touched = added = 0
for article in rows:
    sections = list(article.sections or [])
    total = 0
    for index, section in enumerate(sections):
        body = section.get("content") or ""
        fixed, count = autolink.apply(body, matchers, skip=article.slug)
        if count:
            sections[index] = {**section, "content": fixed}
            total += count
    if total:
        touched += 1
        added += total
        if not DRY:
            article_service.snapshot(db, article, None, note="cross-references linked")
            article.sections = sections
            db.add(article)

if not DRY:
    db.commit()
print(f"{'would add' if DRY else 'added'} {added} cross-references across {touched} articles")
db.close()
