"""Check numerical extraction against a pinned public JATS table; never run source content."""
import hashlib,json,sys
from pathlib import Path
import xml.etree.ElementTree as ET

ROOT=Path(__file__).resolve().parents[1]
def extract(path):
    info=json.loads((ROOT/'data/source-provenance.json').read_text())
    content=Path(path).read_bytes()
    assert len(content)==info['bytes']
    assert 'sha256:'+hashlib.sha256(content).hexdigest()==info['sha256']
    root=ET.fromstring(content)
    tables=[t for t in root.findall('.//table-wrap') if t.get('id')==info['table_id']]
    assert len(tables)==1
    rows=[[' '.join(' '.join(c.itertext()).split()) for c in row] for row in tables[0].findall('.//tr')]
    assert rows[0][1:3]==['Ivermectin','Usual Care']
    out=[]
    for cohort,header,positions in [('primary',1,[4,5,6]),('sensitivity',7,[9,10,11])]:
        totals=[int(rows[header][c].removeprefix('(N = ').removesuffix(')')) for c in [1,2]]
        for month,pos in zip([3,6,12],positions):
            cells=rows[pos]
            assert cells[0].split()[:2]==[str(month),'months']
            pairs=[list(map(int,cells[c].split()[0].split('/'))) for c in [1,2]]
            out.append({'id':f'{cohort}_{month}','cohort':cohort,'month':month,
                        'treatment':{'recovered':pairs[0][0],'observed':pairs[0][1],'cohort':totals[0]},
                        'control':{'recovered':pairs[1][0],'observed':pairs[1][1],'cohort':totals[1]},
                        'source_table':'tbl0015','source_row_zero_based':pos})
    return out
if __name__=='__main__':
    rows=extract(sys.argv[1]);expected=json.loads((ROOT/'data/extraction.json').read_text())
    assert rows==expected
    (ROOT/'results/source-check.json').write_text(json.dumps({'passed':True,'rows':len(rows),'count_cells':len(rows)*6},indent=2)+'\n')
    print('Pinned source extraction verified:',len(rows),'rows')
