"""Put back the cross-references the self-reference rule removed.

The rule was mine to apply and the user has overruled it: linking an article's
own subject is allowed, and they tune links by hand. Each article was
snapshotted before the removal, so the restore is that snapshot's sections —
exact, not reconstructed.
"""
import sys

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

DRY = "--apply" not in sys.argv
NOTE = "self-referential links removed"

db = SessionLocal()
rows = db.query(ArticleRevision).filter(ArticleRevision.note == NOTE).all()
print(f"{len(rows)} snapshots to restore from")
restored = 0
for revision in rows:
    article = db.get(Article, revision.article_id)
    if not article or article.deleted_at is not None:
        print("  skipped, gone:", revision.article_id)
        continue
    if article.sections == revision.sections:
        continue
    if not DRY:
        # Snapshot the current state too, so the undo is itself undoable.
        article_service.snapshot(db, article, None, note="self-referential links restored")
        article.sections = revision.sections
        db.add(article)
    restored += 1
if not DRY:
    db.commit()
    for revision in rows:
        article = db.get(Article, revision.article_id)
        if article:
            article_service.reindex(db, article)
print(f"{'would restore' if DRY else 'restored'} {restored} articles")
db.close()
