"""Complete, order-independent, CRC-verified scan of public stored ZIP members."""
import argparse,zipfile,pathlib,urllib.request,zlib,hashlib,json,datetime,time,concurrent.futures
from http_zip import RemoteFile,member_start

def scan(source,remote,info,lo,hi,out):
    start=member_start(remote,info);end=start+info.file_size-1
    request=urllib.request.Request(remote.url,headers={'Range':'bytes=%d-%d'%(start,end),'User-Agent':'public-summary-research/1.0'})
    want_range='bytes %d-%d/%d'%(start,end,remote.size)
    crc=0;sha=hashlib.sha256();n=0;rows=0;retained=[];remainder=b'';header=None;last_report=0;began=time.monotonic();global_inversions=0;last_key=None
    with urllib.request.urlopen(request,timeout=120) as response:
        if response.status!=206 or response.headers.get('Content-Range')!=want_range:raise ValueError('Source range mismatch')
        while True:
            chunk=response.read(8*1024*1024)
            if not chunk:break
            n+=len(chunk);crc=zlib.crc32(chunk,crc);sha.update(chunk)
            data=remainder+chunk;lines=data.split(b'\n');remainder=lines.pop()
            for line in lines:
                if not line:continue
                if header is None:
                    header=line
                    if header.split(b'\t')[:3]!=[b'MARKERNAME',b'CHR',b'POS']:raise ValueError('Unexpected source header')
                    continue
                rows+=1;f=line.split(b'\t',3)
                key=f[0]
                if last_key is not None and key<last_key:global_inversions+=1
                last_key=key
                if len(f)<4:raise ValueError('Malformed source row')
                if f[1]==b'19' and lo<=int(f[2])<=hi:retained.append(line)
            if n-last_report>=256*1024*1024:
                print(json.dumps({'member':info.filename,'bytes_scanned':n,'total':info.file_size,'rows':rows,'region_rows':len(retained),'seconds':round(time.monotonic()-began,1)}),flush=True);last_report=n
    if remainder:
        rows+=1;f=remainder.split(b'\t',3)
        if f[1]==b'19' and lo<=int(f[2])<=hi:retained.append(remainder)
    if n!=info.file_size or crc!=info.CRC:raise ValueError('Full source CRC/size check failed')
    # Source order is not genomic or lexicographic. Sort only after full scan.
    retained.sort(key=lambda line:(int(line.split(b'\t',3)[2]),line.split(b'\t',1)[0]))
    blob=header+b'\n'+b'\n'.join(retained)+b'\n';out.write_bytes(blob)
    meta={'source':source,'archive_bytes':remote.size,'archive_etag':remote.etag,'member':info.filename,'member_bytes':n,'member_crc32':'%08x'%crc,'crc_verified':True,'member_sha256':sha.hexdigest(),'source_rows_scanned':rows,'global_lexicographic_inversions':global_inversions,'region':{'chromosome':'19','start':lo,'end':hi,'build':'GRCh38'},'region_rows':len(retained),'extract_sha256':hashlib.sha256(blob).hexdigest(),'fetched_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'elapsed_seconds':round(time.monotonic()-began,2),'method':'Complete stored-ZIP-member HTTP range stream, numeric CHR/POS filter, full CRC and SHA256, numeric sort of retained rows'}
    out.with_suffix(out.suffix+'.provenance.json').write_text(json.dumps(meta,indent=2)+'\n');print(json.dumps({'COMPLETE':meta}),flush=True);return meta

def main():
    p=argparse.ArgumentParser();p.add_argument('--out',required=True);p.add_argument('--workers',type=int,default=2);p.add_argument('--members',nargs='+',required=True);args=p.parse_args()
    source='https://api.kpndataregistry.org/api/d/t76dhP';remote=RemoteFile(source);z=zipfile.ZipFile(remote);out=pathlib.Path(args.out);out.mkdir(parents=True,exist_ok=True)
    # Resolve all local header starts before threads share the read cache.
    infos=[z.getinfo(x) for x in args.members]
    for i in infos:member_start(remote,i)
    with concurrent.futures.ThreadPoolExecutor(args.workers) as pool:
        tasks=[pool.submit(scan,source,remote,i,44668207,46683722,out/(i.filename+'.region.tsv')) for i in infos]
        for t in tasks:t.result()
if __name__=='__main__':main()
