"""Catalog public external candidate sources without opening their image pixels."""
import collections,csv,hashlib,json,re,zipfile,xml.etree.ElementTree as ET
from pathlib import Path
R=Path(__file__).resolve().parents[1];D=R/'datasets/r112-external-candidates';O=R/'results/r112/external-reference-sources';F=D/'freshbar';P=D/'repod';NS={'x':'http://schemas.openxmlformats.org/spreadsheetml/2006/main'}
def digest(p,algo='sha256'):
 h=hashlib.new(algo)
 with open(p,'rb') as f:
  for b in iter(lambda:f.read(1024*1024),b''):h.update(b)
 return h.hexdigest()
def read_references(path):
 with zipfile.ZipFile(path) as z:
  workbook=ET.fromstring(z.read('xl/workbook.xml'));sheets=workbook.find('x:sheets',NS);assert sheets[0].attrib['name']=='References';ss=[''.join(x.itertext()) for x in ET.fromstring(z.read('xl/sharedStrings.xml')).findall('x:si',NS)];root=ET.fromstring(z.read('xl/worksheets/sheet1.xml'));out=[]
  for row in root.findall('x:sheetData/x:row',NS):
   cells={}
   for c in row.findall('x:c',NS):
    col=re.match('[A-Z]+',c.attrib['r']).group();v=c.find('x:v',NS);value=v.text if v is not None and v.text is not None else ''
    if c.get('t')=='s' and value:value=ss[int(value)]
    elif c.get('t')=='inlineStr':value=''.join(c.find('x:is',NS).itertext())
    if col in ('B','C','D','E'):cells[col]=value.strip()
   if cells:out.append([cells.get(k,'') for k in ('B','C','D','E')])
 assert out[0]==['Image number','Expert group','Expert genus','Expert Species'];return out[1:]
def main():
 api=json.loads((P/'record.json').read_text())['data'];assert api['persistentUrl']=='https://doi.org/10.18150/YJJB05' and (api['latestVersion']['versionNumber'],api['latestVersion']['versionMinorNumber'])==(1,0);files={x['dataFile']['filename']:x['dataFile'] for x in api['latestVersion']['files']};assert digest(P/'README_RepOD_phytoplankton_AI.txt','md5')==files['README_RepOD_phytoplankton_AI.txt']['checksum']['value'] and digest(P/'Supplementary_Table_S2.xlsx','md5')==files['Supplementary_Table_S2.xlsx']['checksum']['value'];archive=files['File_S3_Stage_2_files.zip'];assert archive['id']==121987 and archive['checksum']['value']=='0f690e844be673a8489590513667450c'
 refs=read_references(P/'Supplementary_Table_S2.xlsx');assert len(refs)==157;ids=[x[0] for x in refs];assert len(set(ids))==157 and set(ids)=={f'{i:03d}' for i in range(1,158)};old=set(json.loads((R/'results/r112/species-scaleup/selection.json').read_text())['per_name'])|set(json.loads((R/'results/r112/species-breadth/selection.json').read_text())['per_name']);reserved=[]
 for ident,group,genus,species in refs:
  name=(genus+' '+species).strip();reserved.append({'stage':'stage2','image_id':ident,'source_group':group,'source_genus':genus,'source_species_epithet':species,'source_name':name,'exact_literal_match_to_existing_source_names':name in old,'independence_status':'unknown; no specimen/sample grouping in reference table','status':'reserved external candidate; not training data'})
 diatoms=[x for x in reserved if x['source_group']=='Bacillariophyta'];assert len(diatoms)==17
 with (F/'LM_pictures.tsv').open(encoding='utf-8-sig',newline='') as f:fresh=list(csv.DictReader(f,delimiter='\t'))
 assert len(fresh)==664 and all('Folder (genus)' in x and 'Folder (species)' in x and 'image' in x for x in fresh);types=collections.Counter(x['type of image'].strip() for x in fresh);folder=collections.Counter(x['Folder (species)'].strip() for x in fresh);culture={x['culture'].strip() for x in fresh if x['culture'].strip()};mixed=sum('enriched culture' in x['culture'].lower() for x in fresh);notice=(F/'archive-notice-2026-12-03.html').read_text();assert 'temporarily closed' in notice
 files_sha={str(x.relative_to(R)):digest(x) for x in (F/'LM_pictures.tsv',F/'mapfiles.txt',F/'FRESHBAR_picture_images_SLU_archive.xlsx',F/'archive-notice-2026-12-03.html',P/'record.json',P/'README_RepOD_phytoplankton_AI.txt',P/'Supplementary_Table_S2.xlsx',R/'results/r112/species-scaleup/selection.json',R/'results/r112/species-breadth/selection.json',Path(__file__))}
 report={'format':'r112-external-reference-metadata-v1','inputs_sha256':files_sha,'freshbar':{'metadata_url':'https://researchdata.se/en/catalogue/dataset/2025-373','image_collection_handle':'https://hdl.handle.net/20.500.12703/6968','light_microscopy_handle':'https://hdl.handle.net/20.500.12703/6822','published_image_license':'CC0 1.0 according to dataset catalogue','metadata_rows':len(fresh),'folder_groups':len(folder),'top_level_genus_folder_labels':len({x['Folder (genus)'].strip() for x in fresh}),'type_of_image_counts':dict(types),'nonempty_exact_culture_strings':len(culture),'rows_with_enriched_culture_text':mixed,'matching_existing_exact_source_name_strings':sorted(set(folder)&old),'image_access_observation':'On 2026-12-03 UTC, the archive handle returned an upgrade notice stating that its frontend was temporarily closed; status may change. No archive image pixels were obtained.','grouping_warning':'Rows, cultures and descendant strains are not necessarily independent. Metadata contain genus-only, qualified, mixed or complex labels and SEM entries. Culture strings are not a validated biological split. Calibration must be checked per image. All images reserved as a potential independent-source candidate pending metadata, lineage, accessibility, licensing and prior-exposure audit.'},'repod':{'dataset_url':'https://doi.org/10.18150/YJJB05','archive_datafile_id':121987,'archive_expected_bytes':archive['filesize'],'archive_published_md5':archive['checksum']['value'],'published_license':'CC BY-SA 4.0 according to repository; attribution and share-alike requirements must be assessed for downstream derivatives','reference_rows':len(refs),'reference_group_counts':dict(collections.Counter(x[1] for x in refs)),'diatom_candidate_count':len(diatoms),'diatom_reference_names':dict(collections.Counter(x['source_name'] for x in diatoms)),'diatom_exact_literal_matches_to_selected_ude_names':sorted({x['source_name'] for x in diatoms if x['exact_literal_match_to_existing_source_names']}),'reference_note':'Stage 2 images are labeled by the dataset authors; repeated names may represent related images or the same organism. This table does not establish independent specimens or scale. The dataset already reports outputs of GPT-5.6 Sol on these images, so that model was previously exposed; other prior training or model exposure is unknown. Preserve all 157 stage-2 and 30 stage-1 image cases as external evaluation candidates, not training inputs, pending detailed independence, overlap, and rights review.','reserved_stage2_records':reserved},'limits':'Metadata and sample-level identifiers do not prove external biological independence, taxonomy correctness, image quality or Academy similarity. No image pixels are opened by this metadata audit. Neither collection is a validated species benchmark.'};(O/'metadata-audit.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps({'freshbar_rows':len(fresh),'freshbar_types':dict(types),'repod_reference_rows':len(refs),'repod_diatoms':len(diatoms),'repod_diatom_names':report['repod']['diatom_reference_names']},indent=2))
if __name__=='__main__':main()
