"""Freeze allele-aligned records from preregistered public source releases.

Run after complete downloads/checksum scans; never substitute an LD proxy.
No participant-level data or identifying reference-panel records enter outputs.
"""
import csv,json,pathlib,hashlib,gzip,io,argparse,shutil,math
import os
root=pathlib.Path(os.environ.get('SJ_SOURCE_ROOT', '.'))
variants=[
 {'rsid':'rs1800437','protein':'E354Q','role':'primary','effect_allele':'C','other_allele':'G','GRCh38':45678134,'GRCh37':46181392},
 {'rsid':'rs139215588','protein':'R190Q','role':'secondary','effect_allele':'A','other_allele':'G','GRCh38':45674762,'GRCh37':46178020},
 {'rsid':'rs143430880','protein':'E288G','role':'secondary','effect_allele':'G','other_allele':'A','GRCh38':45677718,'GRCh37':46180976},
 {'rsid':'rs115338345','protein':'R101H','role':'secondary','effect_allele':'A','other_allele':'G','GRCh38':45672872,'GRCh37':46176130},
 {'rsid':'rs1964272','protein':'SNRPD2 control','role':'local_control','effect_allele':'A','other_allele':'G','GRCh38':45687010,'GRCh37':46190268},
 {'rsid':'rs7412','protein':'APOE control','role':'local_control','effect_allele':'T','other_allele':'C','GRCh38':44908822,'GRCh37':45412079},
 {'rsid':'rs429358','protein':'APOE control','role':'local_control','effect_allele':'C','other_allele':'T','GRCh38':44908684,'GRCh37':45411941}
]
# Confirm source annotations instead of relying solely on manually keyed coordinates.
for v in variants:
 p=root/'sources'/('ensembl37-'+v['rsid'])
 r=json.loads(p.read_text()); mappings=[x for x in r['mappings'] if x['seq_region_name']=='19' and x['assembly_name']=='GRCh37']
 assert any(x['start']==v['GRCh37'] and set(x['allele_string'].split('/'))=={v['effect_allele'],v['other_allele']} for x in mappings),v

def dump(p,x):p.write_text(json.dumps(x,indent=2,allow_nan=False)+'\n')
def read_table(p):
 with p.open() as f:return list(csv.DictReader(f,delimiter='\t'))
def record(ds,v,rows,fields):
 # fields = chromosome, position, effect allele, other allele, beta, SE, P, AF
 chrom,pos,ea,oa,beta,se,p,af=fields
 found=[r for r in rows if str(r[chrom]).removeprefix('chr')=='19' and int(r[pos])==v[ds['assembly']] and {r[ea].upper(),r[oa].upper()}=={v['effect_allele'],v['other_allele']}]
 if len(found)>1:raise ValueError('Duplicate source records '+ds['id']+' '+v['rsid'])
 common={'dataset':ds['id'],'outcome':ds['outcome'],'beta_scale':ds['beta_scale'],'variant':v['rsid'],'protein':v['protein'],'role':v['role'],'effect_allele':v['effect_allele'],'other_allele':v['other_allele'],'source_assembly':ds['assembly'],'source_position':v[ds['assembly']]}
 if not found:return dict(common,available=False,missing_reason='No exact allele-pair record in the complete fixed regional source extract',source_record=None)
 r=found[0];direction=1 if r[ea].upper()==v['effect_allele'] else -1
 b=float(r[beta]);s=float(r[se]);f=float(r[af]);ps=float(r[p])
 if not all(math.isfinite(x) for x in [b,s,f,ps]) or s<=0 or not 0<=f<=1 or not 0<=ps<=1:raise ValueError('Invalid source estimate '+ds['id']+' '+v['rsid'])
 if 'rs_id' in r and r['rs_id'] not in [v['rsid'],'NA','.']:raise ValueError('Unexpected rsID at fixed coordinate')
 return dict(common,available=True,missing_reason=None,beta=b*direction,se=s,p_source=ps,effect_allele_frequency=f if direction==1 else 1-f,n_studies=int(r['N_Studies']) if 'N_Studies' in r else None,source_effect_allele=r[ea],beta_flipped=direction==-1,source_record=r)

def main():
 ap=argparse.ArgumentParser();ap.add_argument('--allow-pending',action='store_true');args=ap.parse_args();data=root/'bundle/data';data.mkdir(parents=True,exist_ok=True);datasets=[];observations=[]
 entries=[('EUR','CAS_AUT_EA_101023.final',80823,2464395),('ALL','CAS_AUT_ALL_101023.final',86864,2853408),('female','CAS_AUT_F_101023.final',22639,1102928),('male','CAS_AUT_M_101023.final',55795,1526601),('AFR','CAS_AUT_AA_082223.final',3126,144150),('HIS','CAS_AUT_HA_082223.final',1403,66444),('EAS','BBJ_EAS_AUT_ALL.nodup.final',1403,131663),('SAS','GH_SAS_AUT_ALL.nodup.final',109,43950)]
 for label,name,cases,total in entries:
  p=root/'sources/small-2025'/(name+'.region.tsv');prov=json.loads(p.with_suffix(p.suffix+'.provenance.json').read_text());assert prov['crc_verified'];assert hashlib.sha256(p.read_bytes()).hexdigest()==prov['extract_sha256']
  rows=read_table(p);assert len(rows)==prov['region_rows'];assert len({r['MARKERNAME'] for r in rows})==len(rows)
  ds={'id':'IAVGC_'+label,'outcome':'clinical aortic stenosis','beta_scale':'log_odds','assembly':'GRCh38','source':prov['source'],'source_file':name,'source_sha256':prov['member_sha256'],'extract_sha256':prov['extract_sha256'],'source_rows_scanned':prov['source_rows_scanned'],'region_rows':len(rows),'resource_cases_max':cases,'resource_total_max':total,'participant_counts_note':'Resource-level counts from the publication, not variant-specific N. Cohorts and variants may differ. Do not add overlapping datasets.','source_qc':{'crc_verified':True,'lexicographic_inversions':prov['global_lexicographic_inversions']}}
  datasets.append(ds)
  se_column='SE' if not rows or 'SE' in rows[0] else 'SELD'
  ds['standard_error_column']=se_column
  ds['standard_error_note']='Meta-analysis SE, or LDSC-corrected SELD in one-cohort EAS/SAS files. Original SEREG and source P are retained in each original row.'
  for v in variants:observations.append(record(ds,v,rows,['CHR','POS','EA','NEA','BETA',se_column,'P','EAF']))
  if label=='EUR':
   with (data/'primary-region.tsv.gz').open('wb') as f:
    with gzip.GzipFile(filename='',mode='wb',fileobj=f,mtime=0) as g:g.write(p.read_bytes())
  if label=='HIS' and not rows:ds['availability_note']='Full CRC-verified source has chromosome-19 records, but none in the prespecified GIPR +/-1 Mb interval. This is an availability limitation, not a null association.'
 # Use the raw, explicitly un-MTAG files, never the indexed MTAG-processed files.
 for name,outcome,scale,total in [
  ('raw.aortic_stenosis.tsv','clinical AS meta-analysis (overlapping cohorts)','source_scale_unresolved',None),
  ('raw.resint_AVACM2.tsv','valve_area','standardized_inverse_normal',59569),
  ('raw.resint_peak_velocity_aa.tsv','peak_velocity','standardized_inverse_normal',59571),
  ('raw.resint_systole_pos_MeanPeakGradientMMHg_aa.tsv','mean_gradient','standardized_inverse_normal',59571)]:
  p=root/'sources/kany-2025-raw'/(name+'.region.tsv')
  if not p.exists():
   if args.allow_pending:continue
   raise ValueError('Required un-MTAG source still pending: '+name)
  prov=json.loads(p.with_suffix(p.suffix+'.provenance.json').read_text());assert prov['source_checksum_verified'];assert hashlib.sha256(p.read_bytes()).hexdigest()==prov['extract_sha256'];rows=read_table(p);assert len(rows)==prov['region_rows']
  ds={'id':'Kany_'+outcome.split()[0],'outcome':outcome,'beta_scale':scale,'assembly':'GRCh37','source':prov['source'],'source_file':name,'source_sha256':prov['source_sha256'],'source_md5':prov['source_md5'],'source_checksum_verified':True,'extract_sha256':prov['extract_sha256'],'source_rows_scanned':prov['source_rows'],'region_rows':len(rows),'resource_total_max':total,'resource_cases_max':None,'participant_counts_note':'Imaging resource N, not variant-specific N. AS meta-analysis overlaps IAVGC and FinnGen; never treat as independent replication.','source_processing':'raw prefix: original METAL AS meta-analysis or original REGENIE quantitative-trait GWAS, not MTAG output (Zenodo description).'}
  datasets.append(ds)
  for v in variants:observations.append(record(ds,v,rows,['chromosome','base_pair_location','effect_allele','other_allele','beta','standard_error','p_value','effect_allele_frequency']))
 p=root/'sources/finngen-r13/I9_CAVS_OPERATED.region.tsv';prov=json.loads(p.with_suffix(p.suffix+'.provenance.json').read_text());assert hashlib.sha256(p.read_bytes()).hexdigest()==prov['sha256'];rows=read_table(p)
 ds={'id':'FinnGen_R13_operated','outcome':'operated calcific aortic stenosis','beta_scale':'log_odds','assembly':'GRCh38','source':prov['source'],'source_file':'finngen_R13_I9_CAVS_OPERATED.gz','extract_sha256':prov['sha256'],'region_rows':len(rows),'resource_cases_max':13490,'resource_controls_max':486696,'resource_total_max':500186,'participant_counts_note':'Different, intervention-dependent endpoint. Cohort overlaps IAVGC; no independent replication or pooling with IAVGC.'};datasets.append(ds)
 for v in variants:observations.append(record(ds,v,rows,['chrom','pos','alt','ref','beta','sebeta','pval','af_alt']))
 dump(data/'variant-definitions.json',variants);dump(data/'datasets.json',datasets);dump(data/'association-inputs.json',observations)
 shutil.copyfile(root/'results/ld-reference.json',data/'ld-reference.json')
 dump(data/'study-spec.json',{'primary_dataset':'IAVGC_EUR','primary_variant':'rs1800437','confidence_level':0.95,'primary_alpha':0.05,'rare_as_family_size':3,'imaging_family_size':12,'imaging_datasets':['Kany_valve_area','Kany_peak_velocity','Kany_mean_gradient'],'rare_variants':['rs139215588','rs143430880','rs115338345'],'precision_reference_OR':[0.90,1.10],'conditioning_controls':['rs1964272','rs7412','rs429358'],'maximum_matrix_condition_number':100,'minimum_reference_minor_allele_count':20,'optional_coloc':'Not undertaken: no detectable primary AS association, no validated exposure scale and no need to turn a low-power regional absence into a posterior causal claim.'})
 print('Curated datasets',len(datasets),'fixed records',len(observations),'available',sum(x['available'] for x in observations),'pending allowed',args.allow_pending)
if __name__=='__main__':main()
