"""Read an officially linked public indexed FinnGen summary region, no form data."""
import pathlib,json,urllib.request,hashlib,datetime,pysam,csv
import os
root=pathlib.Path(os.environ.get('SJ_SOURCE_ROOT', '.'));out=root/'sources/finngen-r13';out.mkdir(exist_ok=True)
manifest=list(csv.DictReader((root/'metadata/finngen-R13-manifest.tsv').open(),delimiter='\t'));record=next(x for x in manifest if x['phenocode']=='I9_CAVS_OPERATED');url=record['path_https'];index=out/'I9_CAVS_OPERATED.gz.tbi'
if not index.exists():index.write_bytes(urllib.request.urlopen(url+'.tbi',timeout=90).read())
t=pysam.TabixFile(url,index=str(index));print('contigs',t.contigs,'header',t.header,flush=True)
rows=list(t.fetch('19',44668206,46683722));header='\n'.join(t.header).lstrip('#');blob=(header+'\n'+'\n'.join(rows)+'\n').encode();p=out/'I9_CAVS_OPERATED.region.tsv';p.write_bytes(blob)
r={'source':url,'manifest_source':'https://storage.googleapis.com/finngen-public-data-r13/summary_stats/finngen_R13_manifest.tsv','phenotype':record,'region':{'build':'GRCh38','chromosome':'19','start':44668207,'end':46683722},'rows':len(rows),'sha256':hashlib.sha256(blob).hexdigest(),'index_sha256':hashlib.sha256(index.read_bytes()).hexdigest(),'fetched_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'access':'Publicly linked indexed summary data; no personal details submitted, no controlled-access credentials used.'};p.with_suffix(p.suffix+'.provenance.json').write_text(json.dumps(r,indent=2)+'\n');print(json.dumps(r),flush=True)
