"""Before/after on the live corpus."""
import time, sys
from app.database import SessionLocal
from app.services import search_service as ss
from app.services import rerank_service as rs

db = SessionLocal()
print("model:", rs.rerank_model(), "configured:", rs.is_configured())

QUERIES = [
    "what causes croup",
    "management of bronchiolitis in an infant",
    "when do you image a first febrile seizure",
    "how do you treat a neonate with jaundice at 20 hours of life",
    "child limping with a fever and refusing to bear weight",
    "iron deficiency anemia in a toddler who drinks a lot of cow milk",
    "murmur that disappears when the child lies down",
    "vomiting projectile in a 4 week old boy",
    "swollen red eye in a newborn on day 2",
    "teenager with knee pain worse after sport",
    "what antibiotic for otitis media if allergic to penicillin",
    "delayed passage of meconium",
]

def body(kind, ids):
    table, _ = ss.CORPORA[kind]
    from sqlalchemy import bindparam, text
    if not ids: return {}
    st = text(f"SELECT id, {ss.RERANK_TEXT[kind]} AS b FROM {table} WHERE id IN :ids").bindparams(bindparam("ids", expanding=True))
    return {r.id: (r.b or "")[:110].replace("\n"," ") for r in db.execute(st, {"ids": list(ids)}).fetchall()}

changed = 0
for q in QUERIES:
    for kind in ("question", "article_section"):
        t0=time.perf_counter()
        ranked, _ = ss.hybrid_ids(db, q, kind, limit=200)
        t1=time.perf_counter()
        new = ss.rerank_ids(db, q, kind, ranked)
        t2=time.perf_counter()
        if not ranked: 
            print(f"\n[{kind}] {q!r}: nothing"); continue
        texts = body(kind, set(ranked[:50]) | set(new[:3]))
        same = ranked[0] == new[0]
        changed += 0 if same else 1
        print(f"\n[{kind}] {q!r}  pool={len(ranked)} fuse={1000*(t1-t0):.0f}ms rerank={1000*(t2-t1):.0f}ms top1 {'same' if same else 'CHANGED'}")
        for label, lst in (("before", ranked), ("after ", new)):
            for i, rid in enumerate(lst[:3]):
                print(f"   {label} {i+1}. [{rid}] {texts.get(rid,'?')}")
print("\ntop-1 changed in", changed, "of", len(QUERIES)*2)
