"""Fetch public COCO JSON members only and report their structure and split overlap."""
import collections
import json
import zipfile
from pathlib import Path

from r16_archive_inspect import Remote

ROOT=Path(__file__).resolve().parent.parent
DEST=Path('/tmp/diatom-mask-coco')
DEST.mkdir(exist_ok=True)
records=[];image_splits=collections.defaultdict(set)
with zipfile.ZipFile(Remote()) as archive:
    names=[i.filename for i in archive.infolist() if i.filename.lower().endswith('_coco.json')]
    for name in names:
        blob=archive.read(name)
        # Preserve path in metadata, but store only the basename locally.
        (DEST/Path(name).name).write_bytes(blob)
        data=json.loads(blob)
        images=data.get('images',[]);annotations=data.get('annotations',[])
        split=Path(name).parts[-2]
        category=Path(name).parts[1]
        for image in images:image_splits[(category,image.get('file_name',''))].add(split)
        seg=collections.Counter(type(a.get('segmentation')).__name__ for a in annotations)
        records.append({'member':name,'images':len(images),'annotations':len(annotations),
                        'segmentation_types':dict(seg),'categories':data.get('categories',[])})
        print(name,'images',len(images),'annotations',len(annotations),dict(seg),flush=True)
leaks=[{'category':k[0],'filename':k[1],'splits':sorted(v)} for k,v in image_splits.items() if len(v)>1]
out=ROOT/'results/r16'
(out/'annotation-audit.json').write_text(json.dumps({'files':records,'filename_split_overlaps':leaks},indent=2))
print('filename overlaps across named splits',len(leaks))
