import re, sys; sys.path.insert(0,"/app")
from collections import Counter
from app.database import SessionLocal
from sqlalchemy import text as sa_text
db = SessionLocal()
rows = db.execute(sa_text("SELECT id, question_text, explanation FROM questions")).fetchall()
# Near-misses of the common units: same length, one letter off.
CANON = ["mEq/L","mmol/L","mg/dL","g/dL","g/L","U/L","µmol/L","mm Hg","beats/min","breaths/min","mOsm/kg","ng/mL","fL","mm/h"]
tok = re.compile(r"[A-Za-zµμ]+(?:/[A-Za-zµμ0-9]+)+")
c = Counter(); ids={}
for qid, s, e in rows:
    for t in (s or "", e or ""):
        for m in tok.finditer(t):
            c[m.group(0)] += 1; ids.setdefault(m.group(0), set()).add(qid)
def near(a,b):
    if abs(len(a)-len(b))>1: return False
    if a==b: return False
    if len(a)==len(b): return sum(x!=y for x,y in zip(a,b))==1
    return False
print("=== near-misses of canonical units (<=8 uses) ===")
for t,n in sorted(c.items(), key=lambda kv: kv[1]):
    if n<=8 and any(near(t,x) for x in CANON):
        print(f"{n:4d} {t!r:14s} near={[x for x in CANON if near(t,x)]} ids={sorted(ids[t])[:5]}")
print("\n=== gap check q143 ===")
t = db.execute(sa_text("SELECT question_text FROM questions WHERE id=143")).scalar()
i = t.find("Albumin"); print(repr(t[i:i+120]))
print("\n=== q247 ESR / q342 lipase ===")
for qid, key in [(247,"Erythrocyte"),(342,"Lipase")]:
    x = db.execute(sa_text("SELECT question_text FROM questions WHERE id=:i"),{"i":qid}).scalar()
    j = x.find(key); print(qid, repr(x[j-60:j+70]))
