"""Flag any table row or leftover fragment that looks wrong."""
import re, sys; sys.path.insert(0,"/app")
from app.database import SessionLocal
from sqlalchemy import text as sa_text
from scripts.fix_lab_formatting import repair_units, tabulate_panels
db = SessionLocal()
rows = db.execute(sa_text("SELECT id, question_text FROM questions WHERE question_text IS NOT NULL ORDER BY id")).fetchall()
suspect = 0; total = 0
for qid, t in rows:
    fixed,_ = repair_units(t)
    out, k = tabulate_panels(fixed)
    if not k: continue
    total += 1
    flags = []
    for line in out.split("\n"):
        if not line.startswith("|") or line.startswith("| ---") or line.startswith("| Test"): continue
        cells = [c.strip() for c in line.strip("|").split("|")]
        name = cells[0]
        if name[:1].islower(): flags.append(f"lowercase name: {line}")
        if len(name) > 45: flags.append(f"long name: {line}")
        if len(cells) > 1 and not cells[1]: flags.append(f"empty value: {line}")
        if re.search(r"\b(?:he|she|his|her|the|is|are|of|and|with)\b", name, re.I): flags.append(f"prose name: {line}")
    # leftover prose fragments that begin mid-sentence
    for para in out.split("\n\n"):
        p = para.strip()
        if p.startswith("|") or not p: continue
        if p[:1].islower() or p[:1] in ".;,)":
            flags.append(f"orphan prose: {p[:90]!r}")
    if flags:
        suspect += 1
        print(f"--- {qid} ---")
        for f in flags[:6]: print("   ", f)
print(f"\ntabulated {total}, with flags {suspect}")
