"""Claim the category each kept article says it is in.

The category ids I had carried were transcribed from a report and one of them
(15041) does not exist. An article's own `category_id` is the authority on
where it is filed, so it is read from the row rather than supplied.
"""
from app.database import SessionLocal
from app.models.article import Article, ArticleTopicClaim
from app.models.question_category import QuestionCategory
from app.services import topic_claims

KEPT = [110, 133, 195, 422, 356, 161, 88, 137, 169, 298, 308, 304,
        101, 220, 154, 388, 225, 378, 132, 91]

db = SessionLocal()
made = 0
for article_id in KEPT:
    article = db.get(Article, article_id)
    if not article or article.deleted_at is not None:
        print(f"!! {article_id} missing or trashed")
        continue
    category_id = article.category_id
    if not category_id or not db.get(QuestionCategory, category_id):
        print(f"!! {article_id} '{article.title[:30]}' is filed on {category_id}, "
              "which is not a category — skipped")
        continue
    claim = db.query(ArticleTopicClaim).filter_by(
        article_id=article_id, category_id=category_id, section_id=None).first()
    if claim is None:
        claim = ArticleTopicClaim(article_id=article_id, category_id=category_id,
                                  section_id=None, include_subtopics=True,
                                  fill_only=True, user_id=None)
        db.add(claim)
        db.commit()
        db.refresh(claim)
    linked = topic_claims.apply(db, claim)
    made += linked
    if linked:
        print(f"   {article.title[:36]:36} cat {category_id}: linked {linked}")
print("newly linked:", made)
db.close()
