"""Same query, same model — old article vectors against new ones, and the section corpus."""
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

QUERIES = {
    "surgery for infant stridor that fails to improve": "Laryngomalacia",
    "oral antifungal for scalp ringworm": "Tinea Capitis",
    "endoscopic division of the aryepiglottic folds": "Laryngomalacia",
    "antifungal taken by mouth for weeks with fatty food": "Tinea Capitis",
}
db = SessionLocal()
titles = dict(db.query(Article.id, Article.title).all())
by_title = {v: k for k, v in titles.items()}

def rank(table, lit, target_ids, schema="public"):
    rows = db.execute(sa_text(f"""
        SELECT id, 1 - (embedding <=> CAST(:v AS vector)) sim FROM {schema}.{table}
        WHERE embedding IS NOT NULL ORDER BY embedding <=> CAST(:v AS vector) LIMIT 400
    """), {"v": lit}).fetchall()
    for position, r in enumerate(rows, 1):
        if r.id in target_ids:
            return position, float(r.sim)
    return None, None

for query, target in QUERIES.items():
    aid = by_title[target]
    emb = ss._query_embedding(query)
    lit = "[" + ",".join(str(float(v)) for v in emb) + "]"
    sec_ids = {r.id for r in db.query(ArticleSectionIndex.id).filter(
        ArticleSectionIndex.article_id == aid).all()}
    before_pos, before_sim = rank("articles", lit, {aid}, "before_reindex")
    after_pos, after_sim = rank("articles", lit, {aid}, "public")
    sec_pos, sec_sim = rank("article_section_index", lit, sec_ids)
    floor = ss.SEMANTIC_FLOOR
    def fmt(pos, sim):
        if pos is None:
            return "not retrieved"
        return f"rank {pos:>3}  sim {sim:.3f}  {'ABOVE' if sim >= floor else 'below'} floor"
    print(f"\n{query!r}  ->  {target}")
    print(f"  article vector, before : {fmt(before_pos, before_sim)}")
    print(f"  article vector, after  : {fmt(after_pos, after_sim)}")
    print(f"  section corpus, before : not retrieved  (article had no rows in the index)")
    print(f"  section corpus, after  : {fmt(sec_pos, sec_sim)}")
db.close()
