"""Autolink just the articles the peer has written or rewritten since the run."""
import sys
from app.database import SessionLocal
from app.models.article import Article
from app.services import article_service, autolink

WANT = {223}
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"])
added = 0
for article in rows:
    if article.id not in WANT:
        continue
    sections = list(article.sections or [])
    total = 0
    for index, section in enumerate(sections):
        fixed, count = autolink.apply(section.get("content") or "", matchers, skip=article.slug)
        if count:
            sections[index] = {**section, "content": fixed}
            total += count
    if total and not DRY:
        article_service.snapshot(db, article, None, note="cross-references linked")
        article.sections = sections
        db.add(article)
    if total:
        print(f"  {article.id} {article.title}: {total}")
    added += total
if not DRY:
    db.commit()
print(f"{'would add' if DRY else 'added'} {added}")
db.close()
