"""Full checksum-verified scans of the fixed public raw GWAS releases."""
import pathlib,json,urllib.request,hashlib,datetime,time,concurrent.futures
import os
root=pathlib.Path(os.environ.get('SJ_SOURCE_ROOT', '.'));meta=json.loads((root/'metadata/zenodo.txt').read_text());out=root/'sources/kany-2025-raw';out.mkdir(exist_ok=True)

def scan(f):
 url=f['links']['self'];n=0;sha=hashlib.sha256();md5=hashlib.md5();rows=0;keep=[];header=None;rem=b'';began=time.monotonic();last=0
 with urllib.request.urlopen(url,timeout=120) as response:
  while True:
   chunk=response.read(8*1024*1024)
   if not chunk:break
   n+=len(chunk);sha.update(chunk);md5.update(chunk);lines=(rem+chunk).split(b'\n');rem=lines.pop()
   for line in lines:
    if not line:continue
    if header is None:
     header=line
     if not header.startswith(b'chromosome\tbase_pair_location\t'):raise ValueError('Unexpected header')
     continue
    rows+=1;v=line.split(b'\t',2)
    if v[0]==b'19' and 45171502<=int(v[1])<=47186982:keep.append(line)
   if n-last>=512*1024*1024:print(json.dumps({'file':f['key'],'bytes':n,'total':f['size'],'rows':rows,'region_rows':len(keep),'seconds':round(time.monotonic()-began,1)}),flush=True);last=n
 if rem:
  rows+=1;v=rem.split(b'\t',2)
  if v[0]==b'19' and 45171502<=int(v[1])<=47186982:keep.append(rem)
 if n!=f['size'] or 'md5:'+md5.hexdigest()!=f['checksum']:raise ValueError('Source size/MD5 verification failed for '+f['key'])
 keep.sort(key=lambda line:(int(line.split(b'\t',2)[1]),line))
 blob=header+b'\n'+b'\n'.join(keep)+b'\n';p=out/(f['key']+'.region.tsv');p.write_bytes(blob)
 provenance={'source':url,'record':'https://zenodo.org/records/'+str(meta['id']),'record_doi':meta.get('doi'),'license':meta.get('metadata',{}).get('license'),'file':f['key'],'source_bytes':n,'source_md5':md5.hexdigest(),'source_sha256':sha.hexdigest(),'source_checksum_verified':True,'source_rows':rows,'region':{'assembly':'GRCh37','chromosome':'19','start':45171502,'end':47186982,'basis':'authoritative GRCh37 GIPR gene boundaries +/-1 Mb'},'region_rows':len(keep),'extract_sha256':hashlib.sha256(blob).hexdigest(),'fetched_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'seconds':round(time.monotonic()-began,1)}
 p.with_suffix(p.suffix+'.provenance.json').write_text(json.dumps(provenance,indent=2)+'\n');print(json.dumps({'COMPLETE':provenance}),flush=True)
 for line in keep:
  if any((b'\t'+rs+b'\t') in line for rs in [b'rs1800437',b'rs139215588',b'rs143430880',b'rs115338345',b'rs1964272',b'rs7412',b'rs429358']):print('FIXED',f['key'],line.decode(),flush=True)
 return provenance
files=[f for f in meta['files'] if f['key'].startswith('raw.')]
with concurrent.futures.ThreadPoolExecutor(2) as pool:
 for r in pool.map(scan,files):pass
