"""Retrieve a frozen UDE subset with bounded ZIP ranges and CRC checks."""
import argparse
import hashlib
import http.client
import io
import json
import time
import urllib.error
import urllib.request
import zipfile
import zlib
from pathlib import Path

ROOT=Path(__file__).resolve().parent.parent
OUT=ROOT/'results/pilot/ude-adaptation'
URL='https://zenodo.org/records/10410655/files/UDE%20Diatoms%20in%20the%20Wild%202024.zip'
SIZE=2084450931
PREFIX='UDE Diatoms in the Wild 2024/images/'


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
        if self.pos<0:raise ValueError('Negative archive seek')
        return self.pos
    def read(self,n=-1):
        if n<0:n=SIZE-self.pos
        remaining=min(n,max(0,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(524288,min(remaining,1048576))-1)
                request=urllib.request.Request(URL,headers={'Range':f'bytes={self.start}-{end}','Accept-Encoding':'identity'})
                for attempt in range(3):
                    try:
                        with urllib.request.urlopen(request,timeout=45) as response:
                            data=response.read()
                            if response.status!=206 or response.headers.get('Content-Range')!=f'bytes {self.start}-{end}/{SIZE}':
                                raise ValueError('Server returned an incorrect range')
                        break
                    except (urllib.error.URLError,TimeoutError,OSError,http.client.IncompleteRead):
                        if attempt==2:raise
                        time.sleep(attempt+1)
                if len(data)!=end-self.start+1:raise ValueError('Incomplete archive 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():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--selection',type=Path,default=OUT/'selection.json')
    parser.add_argument('--expected-count',type=int,default=96,help='Frozen expected number of selected images')
    args=parser.parse_args()
    frozen=args.selection;out=frozen.parent;data=json.loads(frozen.read_text());rows=data['rows']
    if data.get('format')!='ude-four-species-development-v1' or args.expected_count<1 or len(rows)!=args.expected_count:raise ValueError('Unexpected frozen selection')
    report=out/'download-report.json'
    if report.exists():raise FileExistsError('Download report exists; preserve the original retrieval')
    (out/'images').mkdir(exist_ok=True)
    with zipfile.ZipFile(RemoteArchive()) as archive:
        entries=[(archive.getinfo(PREFIX+r['filename']),r) for r in rows]
        results=[]
        for i,(info,row) in enumerate(sorted(entries,key=lambda item:item[0].header_offset),1):
            if not 0<info.file_size<=4*1024*1024:raise ValueError('Unexpected image size')
            target=out/row['local_file']
            if target.exists():
                blob=target.read_bytes()
                if len(blob)!=info.file_size or (zlib.crc32(blob)&0xffffffff)!=info.CRC:raise ValueError(f'Existing image differs from archive: {target}')
            else:
                blob=archive.read(info)  # zipfile checks CRC.
                temporary=target.with_suffix('.png.partial');temporary.write_bytes(blob);temporary.replace(target)
            results.append({'annotation_id':row['annotation_id'],'split':row['split'],'sha256':hashlib.sha256(blob).hexdigest(),
                            'size':len(blob),'archive_crc32':f'{info.CRC:08x}'})
            if i%8==0 or i==len(rows):print(f'{i}/{len(rows)} images verified',flush=True)
    byhash={};cross=[]
    for r in results:
        for previous in byhash.get(r['sha256'],[]):
            if previous['split']!=r['split']:cross.append([previous['annotation_id'],r['annotation_id']])
        byhash.setdefault(r['sha256'],[]).append(r)
    result={'selection_sha256':hashlib.sha256(frozen.read_bytes()).hexdigest(),'source':URL,
            'images':results,'cross_split_exact_image_duplicates':cross}
    report.write_text(json.dumps(result,indent=2)+'\n')
    print('Cross-split exact duplicates:',len(cross),flush=True)
    if cross:raise ValueError('Cross-split duplicate images require quarantine before modeling')


if __name__=='__main__':main()
