"""Put back the clinical figures the audit was too strict about.

The rule the audit should have had, and now has in writing: a *table*, a
citation, a chart or a nomogram on an unrelated stem is a mis-extraction and
goes. A photograph, radiograph, ultrasound, ECG or microscopy slide is a
clinical figure, and a model's opinion that it does not fit is not enough to
throw it off a question — a tick on a leaf against a July fever, fungal hyphae
against a scaly chest, a recessed chin against a two-week-old's notes are all
exactly right, and were all detached.
"""
import json

from app.database import SessionLocal
from app.models.media import MediaAsset
from app.models.question import Question
from app.models.question_media import QuestionMedia

# Clinical figures: restored.
RESTORE = {903, 1168, 1260, 1477, 1579, 1624, 1760, 1838, 1861, 1882,
           1898, 2070, 2523, 2621, 3247, 3578}

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

db = SessionLocal()
restored, missing = [], []
for question_id in sorted(RESTORE):
    entry = by_id.get(question_id)
    question = db.get(Question, question_id)
    if not entry or not question:
        missing.append(question_id)
        continue
    question.image_path = entry["path"]
    asset = db.query(MediaAsset).filter(MediaAsset.path == entry["path"]).first()
    if asset and not db.query(QuestionMedia).filter_by(
            question_id=question_id, media_id=asset.id).first():
        db.add(QuestionMedia(question_id=question_id, media_id=asset.id))
    restored.append(question_id)
db.commit()
print("restored:", restored)
print("not found:", missing)
print("still detached:", sorted(set(by_id) - RESTORE))
