"""Retrieve six deterministic DIATLAS controls from its ZIP by HTTP ranges."""
import csv
import hashlib
import io
import json
import urllib.request
import zipfile
from pathlib import Path

URL='https://zenodo.org/records/16260887/files/diatoms.zip'
SIZE=1115209674
INDEX=Path('/tmp/diatlas-diatoms.csv')
DEST=Path('/tmp/diatom-diatlas-controls')
CODES=('ADMI','NGRE','APED','HVEN','FSAP','AAMB')


class RemoteArchive(io.RawIOBase):
    def __init__(self):self.pos=0;self.start=0;self.cache=b''
    def readable(self):return True
    def seekable(self):return True
    def tell(self):return self.pos
    def seek(self,offset,whence=0):
        self.pos=offset if whence==0 else self.pos+offset if whence==1 else SIZE+offset
        return self.pos
    def read(self,n=-1):
        if n<0:n=SIZE-self.pos
        remaining=min(n,SIZE-self.pos);parts=[]
        while remaining:
            if not self.start<=self.pos<self.start+len(self.cache):
                self.start=self.pos;end=min(SIZE-1,self.start+max(131072,min(remaining,2097152))-1)
                request=urllib.request.Request(URL,headers={'Range':f'bytes={self.start}-{end}','Accept-Encoding':'identity'})
                with urllib.request.urlopen(request,timeout=60) as response:
                    data=response.read()
                    if response.status!=206 or response.headers.get('Content-Range')!=f'bytes {self.start}-{end}/{SIZE}':
                        raise ValueError('Archive server did not return the exact requested range')
                if len(data)!=end-self.start+1:raise ValueError('Incomplete range')
                self.cache=data
            offset=self.pos-self.start;length=min(remaining,len(self.cache)-offset)
            parts.append(self.cache[offset:offset+length]);self.pos+=length;remaining-=length
        return b''.join(parts)


def main():
    if hashlib.md5(INDEX.read_bytes()).hexdigest()!='be2fc6d2ee5b568869725852e340dd1a':raise ValueError('Unexpected DIATLAS index checksum')
    rows=list(csv.DictReader(INDEX.open()))
    selected=[]
    for code in CODES:
        choices=sorted((r for r in rows if r['species_code']==code and r['scale'] and
                        r['connective'].strip().casefold()=='false' and r['path'].lower().endswith(('.png','.jpg','.jpeg'))),
                       key=lambda r:r['path'])
        if not choices:raise ValueError(f'No eligible records for {code}')
        selected.append(choices[0])
    DEST.mkdir(exist_ok=True)
    with zipfile.ZipFile(RemoteArchive()) as archive:
        names=archive.namelist()
        for i,row in enumerate(selected,1):
            suffix=row['path'].lstrip('/');matches=[n for n in names if n==suffix or n.endswith('/'+suffix)]
            if len(matches)!=1:raise ValueError(f'Ambiguous ZIP entry for {suffix}: {matches}')
            info=archive.getinfo(matches[0]);data=archive.read(info)  # ZIP CRC checked.
            target=DEST/f'{i:02d}{Path(suffix).suffix.lower()}';target.write_bytes(data)
            row.update(zip_member=info.filename,local_file=str(target),sha256=hashlib.sha256(data).hexdigest(),
                       scale_um_per_pixel=float(row['scale'])/100.0)
            print(i,row['species_code'],len(data),'bytes',flush=True)
    (DEST/'selection.json').write_text(json.dumps({'dataset':'10.5281/zenodo.16260887',
        'selection':'first lexical non-connective image with scale for each fixed taxon code',
        'index_md5':'be2fc6d2ee5b568869725852e340dd1a','rows':selected},indent=2)+'\n')


if __name__=='__main__':main()
