import json,sys,struct,math
from pathlib import Path
root=Path(__file__).resolve().parent
assert (root/'source.png').stat().st_size>0
expected=json.loads((root/'expected.json').read_text())
actual=json.loads(Path(sys.argv[1]).read_text()) if len(sys.argv)>1 else expected
assert expected['manual_reference'] is True
data=actual.get('res',actual)
texts=data.get('rec_texts',[x['text'] for x in actual.get('lines',[])])
for line in expected['lines']:assert line['text'] in texts, 'missing: '+line['text']
if len(sys.argv)==1:
    assert all(len(row['bbox'])==4 for row in expected['lines'])
    print('Manual reference structure only; PaddleOCR not executed')
else:
    width,height=struct.unpack('>II',(root/'source.png').read_bytes()[16:24])
    polygons=data.get('rec_polys')
    assert isinstance(polygons,list) and len(polygons)==len(texts), 'missing OCR polygons'
    for poly in polygons:
        assert len(poly)==4,'expected four text box corners'
        for x,y in poly:
            assert math.isfinite(x) and math.isfinite(y)
            assert 0<=x<=width and 0<=y<=height,'box outside original image'
    print('Actual JSON text and polygon bounds PASS; inspect saved OCR image boxes manually')
