"""Run the linker over every published article, with the rules as they now are."""
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
db = SessionLocal()
added = touched = 0
for article in db.query(Article).filter(
        Article.deleted_at.is_(None), Article.status == "published").all():
    before = str(article.sections)
    count = article_service.link_cross_references(db, article)
    if count:
        touched += 1
        added += count
    if DRY:
        db.rollback()
if not DRY:
    db.commit()
print(f"{'would add' if DRY else 'added'} {added} links across {touched} articles")
db.close()
