"""Independent arithmetic check of supplied TESS result tables; imports no study code.
This does not regenerate flux processing or injection trials from the raw FITS data.
Usage: python independent_tables.py /path/to/bundle
"""
import csv,json,sys,math,statistics,collections
from pathlib import Path
b=Path(sys.argv[1])
def read(n):
 with (b/n).open(newline='') as f:return list(csv.DictReader(f))
inj=read('results/injections.csv');null=read('results/null_events.csv');h=[x for x in inj if x['split']=='heldout'];hn=[x for x in null if x['split']=='heldout'];N=len({x['tic'] for x in h});assert N==150 and len(h)==7500
assert all(float(x['best_snr_controls'])<=float(x['best_snr_baseline'])+1e-8 for x in inj)
def threshold(rows,far,control=False):
 a=sorted([float(x['snr']) for x in rows if not control or x['passes_controls']=='1'],reverse=True);k=math.floor(far*N+1e-9);return max(3,math.nextafter(a[k],math.inf)) if len(a)>k else 3
def compare(far):
 tb=threshold(hn,far);tc=threshold(hn,far,True);rb=[float(x['best_snr_baseline'])>=tb for x in h];rc=[float(x['best_snr_controls'])>=tc for x in h]
 return {'far':far,'baseline_threshold':tb,'control_threshold':tc,'baseline_count':sum(rb),'control_count':sum(rc),'difference':(sum(rc)-sum(rb))/len(h),'only_baseline':sum(a and not c for a,c in zip(rb,rc)),'only_controls':sum(c and not a for a,c in zip(rb,rc))}
r3=compare(.1);r2=json.loads((b/'results/R2.json').read_text());tb=r2['baseline']['threshold'];tc=r2['with_controls']['threshold'];r4={'baseline_count':sum(float(x['best_snr_baseline'])>=tb for x in h),'control_count':sum(float(x['best_snr_controls'])>=tc for x in h),'baseline_nulls':sum(float(x['snr'])>=tb for x in hn),'control_nulls':sum(float(x['snr'])>=tc and x['passes_controls']=='1' for x in hn)}
s=[x for x in null if x['split']=='tuning' and float(x['snr'])>=10];c=collections.Counter(x['tic'] for x in s);top=max(c,key=lambda t:(c[t],-int(t)));times=sorted(float(x['time']) for x in s if x['tic']==top)
output={'scope':'Independent arithmetic on supplied CSV outputs, not regeneration of raw-photometry processing','all_injections':len(inj),'heldout_stars':N,'heldout_injections':len(h),'veto_snr_never_increases':True,'C1_counts':r3,'C4_tuning_threshold_counts':r4,'C5_strong_nulls':{'star':int(top),'star_count':c[top],'total':len(s),'median_spacing_days':statistics.median(y-x for x,y in zip(times,times[1:])),'durations_h':sorted({float(x['duration_h']) for x in s if x['tic']==top})},'C6_point_curve':[compare(f) for f in [.02,.05,.1,.2,.5,1.0]]}
print(json.dumps(output,indent=2))
