import asyncio, json, tempfile
from pathlib import Path
import pypdfium2 as pdfium
from quber.agents import grid_locator as gl
from quber.core.extractors.camelot.acquire import render_pages
S=Path('/tmp/claude-1000/-home-mande-repo-quber/bc2f817a-5c6c-4515-9621-2302b82f7f68/scratchpad')
WITH=gl.build_prompt(gl.DEFAULT_ROWS, gl.DEFAULT_COLS)
B="""- Two or more tables printed SIDE BY SIDE, each with its own column-header
  block and its own row-label column, are separate tables. Report each with
  its own column span.
"""
assert B in WITH; WITHOUT=WITH.replace(B,"")
cases=[('ABR99-2 p8','ea79061bb6be6ce0',8),('LFT p11','1c3b154b97076b0e',11),('FBRT p11','16e4d896059a4eff',11),('ABR10Q p19','9df78c83fcebc851',19),('ABR10Q p48','9df78c83fcebc851',48)]
results=[]
async def main():
    for label,key,pg in cases:
        src=pdfium.PdfDocument(str(S/'hosted-pdfs'/f'{key}.pdf')); one=pdfium.PdfDocument.new(); one.import_pages(src,[pg-1]); pdf=S/f'var-{key}-p{pg}.pdf'; one.save(str(pdf))
        with tempfile.TemporaryDirectory() as tmp:
            img=render_pages(pdf, 200, Path(tmp))[0]
            for name,prompt in (('without',WITHOUT),('with',WITH)):
                gl.build_prompt=lambda r,c,_p=prompt: _p
                loc=gl.PydanticAIGridLocator()
                for i in range(3):
                    located=await loc.locate(img, pdf, 1)
                    rec={'page':label,'prompt':name,'run':i+1,'n':len(located),'titles':[t.title[:24] for t in located]}
                    results.append(rec); print(json.dumps(rec), flush=True)
    json.dump(results, open(S/'som_variance5.json','w'), indent=1)
asyncio.run(main())
