"""Recover complete ZIP entries in an already downloaded prefix and join UDE labels."""
import binascii
import csv
import hashlib
import json
import struct
import zlib
from pathlib import Path

ROOT=Path(__file__).resolve().parent.parent
PREFIX=Path('/tmp/ude-diatoms-2024.zip')
META=Path('/tmp/ude-metadata.csv')
OUT=ROOT/'results/r14/prefix'
OUT.mkdir(parents=True,exist_ok=True)
raw=PREFIX.read_bytes()
pos=0;entries=[]
while pos+30<=len(raw) and raw[pos:pos+4]==b'PK\x03\x04':
    (magic,version,flags,method,modtime,moddate,crc,compressed,uncompressed,name_len,extra_len)=struct.unpack_from('<IHHHHHIIIHH',raw,pos)
    name=raw[pos+30:pos+30+name_len].decode('utf-8')
    start=pos+30+name_len+extra_len;end=start+compressed
    if flags&9 or end>len(raw):break  # Reject encrypted or data-descriptor entries and incomplete tails.
    data=raw[start:end]
    if method==8:data=zlib.decompress(data,-15)
    elif method!=0:raise ValueError(f'Unsupported ZIP method {method}')
    if len(data)!=uncompressed or binascii.crc32(data)&0xffffffff!=crc:raise ValueError('ZIP member size/CRC mismatch')
    if name.endswith('.png'):entries.append((name.rsplit('/',1)[-1],data))
    pos=end
names={name for name,_ in entries};labels={}
with META.open(newline='',encoding='utf-8-sig') as f:
    for row in csv.DictReader(f):
        if row['cutout_filename'] in names:
            if row['cutout_filename'] in labels:raise ValueError('Ambiguous metadata filename')
            labels[row['cutout_filename']]=row
if set(labels)!=names:raise ValueError('Missing labels')
rows=[]
for name,data in entries:
    r=labels[name];target=f"reference/{r['annotation_id']}.png"
    (OUT/'reference').mkdir(exist_ok=True)
    (OUT/target).write_bytes(data)
    rows.append({'annotation_id':r['annotation_id'],'genus':r['genus'],'species':r['species'],
                 'source_slide':r['image_filename'].split('.Chunk')[0],
                 'filename':name,'local_file':target,'sha256':hashlib.sha256(data).hexdigest()})
manifest={'description':'Complete image entries recovered from an incomplete locally cached ZIP prefix, not a random sample',
          'source_prefix_sha256':hashlib.sha256(raw).hexdigest(),'metadata_sha256':hashlib.sha256(META.read_bytes()).hexdigest(),
          'last_complete_byte':pos,'rows':rows}
(OUT/'reference-manifest.json').write_text(json.dumps(manifest,indent=2))
print('Recovered',len(rows),'complete CRC-checked PNGs from',len({r['source_slide'] for r in rows}),'source-slide identifiers')
