"""Point today's retirements at their keepers, by id and by slug."""
from app.database import SessionLocal
from app.models.article import Article, ArticleRedirect, ArticleSlug

PAIRS = [
    (129, 110), (273, 168), (348, 133), (288, 195), (278, 422), (322, 356),
    (99, 161), (204, 88), (177, 137), (365, 169), (371, 298), (217, 308),
    (287, 304), (84, 101), (428, 220), (257, 154), (318, 388), (315, 225),
    (228, 378), (270, 132), (447, 232), (496, 484),
]

db = SessionLocal()
made = slugs = 0
for retired, keeper in PAIRS:
    gone, keep = db.get(Article, retired), db.get(Article, keeper)
    if not gone or not keep:
        print(f"!! {retired} -> {keeper}: missing article")
        continue
    if keep.deleted_at is not None:
        print(f"!! {retired} -> {keeper}: the keeper is itself trashed")
        continue

    if not db.query(ArticleRedirect).filter_by(from_article_id=retired).first():
        db.add(ArticleRedirect(from_article_id=retired, to_article_id=keeper))
        made += 1

    # The retired slug follows the id. `article_slugs` is unique on the slug,
    # so an existing row is re-pointed rather than duplicated.
    if gone.slug:
        row = db.query(ArticleSlug).filter_by(slug=gone.slug).first()
        if row is None:
            db.add(ArticleSlug(slug=gone.slug, article_id=keeper))
            slugs += 1
        elif row.article_id != keeper:
            row.article_id = keeper
            slugs += 1
db.commit()
print(f"redirects {made}, slugs pointed at keepers {slugs}")

# Prove it end to end, by id and by slug.
from app.services import article_service
for probe in ("129", "496", db.get(Article, 129).slug):
    found = article_service.resolve_slug(db, probe)
    print(f"  {probe!r:34} -> {found.id if found else None} {found.title[:30] if found else ''}")
db.close()
