from pathlib import Path
import sys,requests,re,json,subprocess,pyarrow.parquet as pq
root=Path(__file__).resolve().parent
base=root.parent
settings=json.loads((base/'settings.json').read_text())
original=(base/'instruction.txt').read_text().strip()
added='Before returning any integer, locate that exact amount in the OCR transcript. If you cannot find it, return null. Do not complete a plausible cash transaction from arithmetic.'
(root/'revised-instruction.txt').write_text(original+'\n'+added+'\n')
def tokens(text):
    return {int(re.sub('[.,]','',s)) for s in re.findall(r'(?<![\d.,])\d{1,3}(?:[.,]\d{3})+(?![\d.,])|(?<![\d.,])\d+(?![\d.,])',text)}
def evaluate(ans,reference,ocr):
    amounts=[ans[k] for k in ('total_due','cash_tendered','change')]
    balances=None not in amounts and amounts[0]+amounts[2]==amounts[1]
    return dict(accurate=ans==reference,arithmetic=balances,guard=balances and all(v in tokens(ocr) for v in amounts))
rows=[]
for x in json.loads((base/'scores.json').read_text()):
    if x['route']=='text':
        rows.append(dict(row=x['row'],arm='discovery',**evaluate(x['actual'],x['expected'],(base/'ocr'/(x['row']+'.txt')).read_text())))
frames=next(pq.ParquetFile(sys.argv[1]).iter_batches(batch_size=20)).to_pylist()
def amount(s):
    if s is None:return None
    v=re.sub(r'^Rp\.?\s*','',s,flags=re.I).strip()
    if not re.fullmatch(r'\d+|\d{1,3}(?:[.,]\d{3})+',v):raise ValueError(s)
    return int(re.sub('[.,]','',v))
for i in range(12,20):
    r=frames[i];stem=f'{i:02}';p=root/'images'/(stem+'.png')
    p.write_bytes(r['image']['bytes'])
    subprocess.run(['tesseract',str(p),str(root/'ocr'/stem),'-l','eng','--psm','6'],check=True,capture_output=True)
    ocr=(root/'ocr'/(stem+'.txt')).read_text()
    labels=json.loads(r['ground_truth'])['gt_parse']
    (root/'labels'/(stem+'.json')).write_text(json.dumps(labels,indent=2))
    ref={k:amount(labels.get('total',{}).get(v)) for k,v in zip(('total_due','cash_tendered','change'),('total_price','cashprice','changeprice'))}
    for arm in (('original','revised') if i%2==0 else ('revised','original')):
        prompt=original+ ('\n'+added if arm=='revised' else '')+'\n\nOCR transcript:\n'+ocr
        payload={**settings,'messages':[{'role':'user','content':[{'type':'text','text':prompt}]}]}
        (root/'prompts'/(stem+'-'+arm+'.json')).write_text(json.dumps(payload,indent=2))
        response=root/'responses'/(stem+'-'+arm+'.json')
        if not response.exists():
            rr=requests.post('http://127.0.0.1:58219/v1/chat/completions',json=payload);rr.raise_for_status();response.write_bytes(rr.content)
        ans=json.loads(json.loads(response.read_text())['choices'][0]['message']['content'])
        rows.append(dict(row=stem,arm=arm,expected=ref,actual=ans,**evaluate(ans,ref,ocr)))
(root/'results.json').write_text(json.dumps(rows,indent=2))
for arm in ['discovery','original','revised']:
    arr=[r for r in rows if r['arm']==arm]
    print(arm,len(arr),sum(r['accurate'] for r in arr),[(mode,sum(r[mode] for r in arr),[r['row'] for r in arr if r[mode] and not r['accurate']]) for mode in ('arithmetic','guard')])
