"""Science > Chemistry > Introduction, and file the mole article under it."""
from app.database import SessionLocal
from app.models.article import Article
from app.models.question_category import QuestionCategory
from app.services import article_service

db = SessionLocal()

def branch(name, parent_id):
    row = db.query(QuestionCategory).filter(
        QuestionCategory.name == name,
        QuestionCategory.parent_id.is_(None) if parent_id is None
        else QuestionCategory.parent_id == parent_id).first()
    if row:
        return row
    row = QuestionCategory(name=name, parent_id=parent_id, user_id=6)
    db.add(row)
    db.commit()
    db.refresh(row)
    return row

science = branch("Science", None)
chemistry = branch("Chemistry", science.id)
intro = branch("Introduction", chemistry.id)
print("tree:", science.id, "→", chemistry.id, "→", intro.id)

article = db.query(Article).filter(Article.slug == "the-mole-concept").first()
article.category_id = intro.id
db.commit()
article_service.reindex(db, article)
print("filed:", article.id, article.title, "→ category", article.category_id)
