"""Raw nearest neighbours, no SEMANTIC_FLOOR, to see what the ranker actually thinks."""
from sqlalchemy import text as sa_text
from app.database import SessionLocal
from app.services import search_service as ss
from app.models.article import Article, ArticleSectionIndex

db = SessionLocal()
titles = dict(db.query(Article.id, Article.title).all())

for term in ["supraglottoplasty", "griseofulvin",
             "surgery for infant stridor that fails to improve",
             "oral antifungal for scalp ringworm"]:
    emb = ss._query_embedding(term)
    lit = "[" + ",".join(str(float(v)) for v in emb) + "]"
    print(f"\n=== {term!r} ===")
    for table, label in (("articles", "article"), ("article_section_index", "section")):
        rows = db.execute(sa_text(f"""
            SELECT id, 1 - (embedding <=> CAST(:v AS vector)) sim FROM {table}
            WHERE embedding IS NOT NULL ORDER BY embedding <=> CAST(:v AS vector) LIMIT 5
        """), {"v": lit}).fetchall()
        for r in rows:
            if label == "article":
                name = titles.get(r.id)
            else:
                s = db.get(ArticleSectionIndex, r.id)
                name = f"{titles.get(s.article_id)}/{s.title}"
            print(f"  {label:8} {r.sim:.3f}  {name}")
print(f"\nSEMANTIC_FLOOR = {ss.SEMANTIC_FLOOR}")
db.close()
