import sys,json,csv,hashlib,re
from pathlib import Path
import numpy as np
sys.path.insert(0,'code')
import selflens as S
import analyze as A
root=Path('data');sample=json.loads((root/'sample.json').read_text())
if sys.argv[1]=='sample':
 with (root/'meta/all_targets_S002_v1.csv').open() as f:
  targets={int(r[0]):float(r[3]) for r in csv.reader(line for line in f if not line.startswith('#')) if r and r[0]!='TICID'}
 pat=re.compile(r'https://\S+-s0002-(\d{16})-\S+-s_lc\.fits')
 urls={int(m.group(1)) for m in pat.finditer((root/'meta/tesscurl_sector_2_lc.sh').read_text())}
 order=sorted((t for t,m in targets.items() if 8<=m<12),key=lambda t:hashlib.sha256(f'tess-selflensing-sample:{t}'.encode()).hexdigest())
 chosen=[t for t in order if t in urls][:300]
 stars=sample['stars'][:300]
 assert chosen==[s['tic'] for s in stars]
 assert [s['split'] for s in stars]==['tuning']*150+['heldout']*150
 for s in stars:
  lc=S.load(root/s['file']);assert S.good_mask(lc).mean()>=.5
 print('Independent random-sample check passed: first 300 ranked available targets all eligible, correct split. Flare-subset selection not checked.')
else:
 recs=A.load('data/sample.json','results/trials');A.add_common_mode(recs)
 ev=A.Events([r for r in recs if r['split']=='heldout']);b=ev.passing(A.BASELINE);d=ev.passing(A.DEFAULT_CONTROLS)
 hb=A.evaluate(ev,b,A.PRIMARY_FAR);hd=A.evaluate(ev,d,A.PRIMARY_FAR)
 boot=A.bootstrap(ev,{'baseline':b,'controls':d},A.PRIMARY_FAR)
 A.write('results','R8',{'controls':A.knobs_json(A.DEFAULT_CONTROLS),'far':A.PRIMARY_FAR,'recovery':A.r4(hd['recovery']),'threshold':A.r4(hd['threshold']),'baseline_recovery':A.r4(hb['recovery']),'difference':A.r4(hd['recovery']-hb['recovery']),'difference_ci':A.ci(boot['difference'])})
 print('R8 recomputed from fresh trials using unchanged analysis functions.')
