p = 'backend/app/routers/media.py'
s = open(p).read()

s = s.replace('''@router.get("/")
def list_media(
    q: str | None = Query(None),
    library_id: int | None = Query(None),
    limit: int = Query(60, le=200),
    offset: int = Query(0),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    """Browse the image bank. `q` searches captions, alt text and titles."""
    scope = readable_libraries(db, current_user)
    query = db.query(MediaAsset)
    if scope is not None:
        query = query.filter(MediaAsset.library_id.in_(scope or {0}))''',
'''#: Where a figure came from. Not a column: a figure is a question's or an
#: article's because something points at it, and the same drawing can be both.
SOURCES = ("question", "article", "unused")


@router.get("/")
def list_media(
    q: str | None = Query(None),
    library_id: int | None = Query(None),
    source: str | None = Query(None, description="question, article or unused"),
    limit: int = Query(60, le=200),
    offset: int = Query(0),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    """Browse the image bank. `q` searches captions, alt text and titles.

    One collection, however a figure got here. A question's figure and a
    diagram drawn for an article are the same kind of thing to anybody looking
    for a picture of a topic, and keeping them in two grids meant reading
    "440" in one place and "291" in another and never seeing the bank. Where
    it came from is a filter, not a wall.
    """
    if source is not None and source not in SOURCES:
        raise HTTPException(422, f"source must be one of {', '.join(SOURCES)}")
    scope = readable_libraries(db, current_user)
    query = db.query(MediaAsset)
    if scope is not None:
        # A figure in no library at all is bank content nobody filed — the
        # Illustrate output was all of it — and it must not vanish for
        # everyone but an administrator just because it has no library row.
        query = query.filter(or_(MediaAsset.library_id.in_(scope or {0}),
                                 MediaAsset.library_id.is_(None)))''')

s = s.replace('''    if q and q.strip():
        ranked, _ = hybrid_ids(db, q.strip(), "media", limit=200)
        if not ranked:
            return {"total": 0, "images": []}
        query = query.filter(MediaAsset.id.in_(ranked))

    total = query.count()''',
'''    if q and q.strip():
        ranked, _ = hybrid_ids(db, q.strip(), "media", limit=200)
        if not ranked:
            return {"total": 0, "images": []}
        query = query.filter(MediaAsset.id.in_(ranked))

    on_question = select(QuestionMedia.media_id)
    on_article = select(ArticleMedia.media_id)
    if source == "question":
        query = query.filter(MediaAsset.id.in_(on_question))
    elif source == "article":
        query = query.filter(MediaAsset.id.in_(on_article))
    elif source == "unused":
        # Nothing points at it. Worth being able to find: it is where the
        # near-duplicates and the leftovers of an abandoned run collect.
        query = query.filter(~MediaAsset.id.in_(on_question),
                             ~MediaAsset.id.in_(on_article))

    total = query.count()''')

s = s.replace('''    used = dict(db.query(QuestionMedia.media_id, func.count(QuestionMedia.id)).filter(
        QuestionMedia.media_id.in_([a.id for a in assets] or [0])
    ).group_by(QuestionMedia.media_id).all()) if assets else {}
    return {"total": total, "images": [
        {**_asset_json(a, tags.get(a.id, [])), "used_by": used.get(a.id, 0)} for a in assets]}''',
'''    ids = [a.id for a in assets] or [0]
    used = dict(db.query(QuestionMedia.media_id, func.count(QuestionMedia.id)).filter(
        QuestionMedia.media_id.in_(ids)
    ).group_by(QuestionMedia.media_id).all()) if assets else {}
    # What an article figure belongs to, by name. A card saying "used in
    # Bronchiolitis" is findable; one saying "used by 1" is a number.
    in_articles: dict[int, list[dict]] = {}
    if assets:
        rows = db.query(ArticleMedia.media_id, Article.id, Article.title,
                        Article.slug, ArticleMedia.section_id).join(
            Article, Article.id == ArticleMedia.article_id).filter(
            ArticleMedia.media_id.in_(ids)).all()
        for media_id, article_id, title, slug, section_id in rows:
            in_articles.setdefault(media_id, []).append(
                {"id": article_id, "title": title, "slug": slug, "section_id": section_id})
    return {"total": total, "images": [
        {**_asset_json(a, tags.get(a.id, [])),
         "used_by": used.get(a.id, 0),
         "articles": in_articles.get(a.id, []),
         # The one word a card needs to say where it came from.
         "source": ("question" if used.get(a.id) else
                    "article" if in_articles.get(a.id) else "unused")}
        for a in assets]}''')
open(p, 'w').write(s)
print('written')
