"""The detached figures are not rubbish — they are somebody else's figure.

Extraction took each one off the page a question was printed on. When that was
wrong, the picture usually belongs to a *neighbouring* question in the same
source document, which is exactly the search this does: describe the figure,
look for the question it describes, and offer the match.

Nothing is attached here. It prints what it found, because putting a picture on
a question is the sort of thing a person should agree to.
"""
import json

from app.database import SessionLocal
from app.models.media import MediaAsset
from app.models.question import Question
from app.services.search_service import hybrid_ids

ORPHANS = [1120, 1143, 1179, 1194, 1196, 1204, 1206, 1235, 1843, 2511, 2514, 2813, 3029, 3638]

report = json.load(open("/tmp/figures.log"))
by_id = {m["question_id"]: m for m in report["mismatches"]}

db = SessionLocal()
for question_id in ORPHANS:
    entry = by_id.get(question_id)
    if not entry:
        continue
    asset = db.query(MediaAsset).filter(MediaAsset.path == entry["path"]).first()
    described = (asset.caption or asset.alt_text or entry["shows"]) if asset else entry["shows"]
    ranked, _ = hybrid_ids(db, described, "question", limit=6)
    # The page it came from, so a neighbour can be preferred: figures land on
    # the question printed nearest them far more often than on a random one.
    page = entry["path"].rsplit("/", 1)[-1]
    print(f"\n=== was on Q#{question_id} · {page}")
    print(f"    figure: {described[:110]}")
    for candidate_id in ranked[:3]:
        question = db.get(Question, candidate_id)
        if not question:
            continue
        has_image = bool(question.image_path)
        near = abs(candidate_id - question_id)
        print(f"    → Q#{candidate_id} {'(has a figure already)' if has_image else '(no figure)'} "
              f"[{near} away] {(question.question_text or '')[:80]}")
