"""Audit preselected public box annotations without fetching microscope images."""
import concurrent.futures,hashlib,json,time,urllib.parse,urllib.request,xml.etree.ElementTree as ET
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r46';TEMP=Path('/tmp/diatom-r46-public/xmls');BASE='https://www.kaggle.com/api/v1/datasets/download/huseyingunduz/diatom-dataset/'
def sha(b):return hashlib.sha256(b).hexdigest()
def fetch(ident):
 path=TEMP/(ident+'.xml');url=BASE+urllib.parse.quote('xmls/'+ident+'.xml',safe='')
 if path.exists():data=path.read_bytes()
 else:
  for attempt in range(3):
   try:
    with urllib.request.urlopen(urllib.request.Request(url,headers={'User-Agent':'diatom-research-audit/1.0'}),timeout=40) as response:data=response.read(262145)
    break
   except (OSError,TimeoutError):
    if attempt==2:raise
    time.sleep(attempt+1)
  if len(data)>262144:raise ValueError('Unexpected XML size')
  path.write_bytes(data)
 root=ET.fromstring(data);w=int(root.findtext('./size/width'));h=int(root.findtext('./size/height'));objects=[]
 for obj in root.findall('./objects/object'):
  box=[int(obj.findtext('./bbox/'+x)) for x in ('xmin','ymin','xmax','ymax')]
  if not (0<=box[0]<box[2]<=w and 0<=box[1]<box[3]<=h):raise ValueError(f'Bad box for {ident}')
  objects.append({'id':obj.findtext('id'),'name':obj.findtext('name'),'box':box})
 pairs=[]
 for i,a in enumerate(objects):
  for j,b in enumerate(objects[i+1:],i+1):
   x=max(0,min(a['box'][2],b['box'][2])-max(a['box'][0],b['box'][0]));y=max(0,min(a['box'][3],b['box'][3])-max(a['box'][1],b['box'][1]));
   if x*y:pairs.append({'indices':[i,j],'box_intersection_area':x*y})
 return {'id':ident,'xml_sha256':sha(data),'size':[w,h],'objects':objects,'overlapping_box_pairs':pairs}
def main():
 selection=(OUT/'metadata-selection.json').read_bytes();data=json.loads(selection);TEMP.mkdir(parents=True,exist_ok=True)
 if (OUT/'box-audit.json').exists():raise FileExistsError('Box audit already exists')
 records=[]
 with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
  futures={pool.submit(fetch,ident):ident for ident in data['selection']}
  for n,future in enumerate(concurrent.futures.as_completed(futures),1):
   records.append(future.result())
   if n%8==0:print(f'{n}/{len(futures)} public XML annotations verified',flush=True)
 order={v:i for i,v in enumerate(data['selection'])};records.sort(key=lambda r:order[r['id']])
 result={'format':'r46-box-audit-v1','selection_sha256':sha(selection),'records':records,'warning':'Bounding box intersection does not establish specimen overlap; source/sample independence and label completeness are unverified.'}
 (OUT/'box-audit.json').write_text(json.dumps(result,indent=2)+'\n');print('Public box audit complete.',flush=True)
if __name__=='__main__':main()
