"""Recompute the complete deterministic selection audit from source files."""
import csv,hashlib,json,shlex
from pathlib import Path
import numpy as np
from astropy.io import fits
sources=Path('data/sources');external=json.loads(Path('data/external.json').read_text())
for e in external:
    raw=Path(e['path']).read_bytes()
    assert len(raw)==e['bytes'] and 'sha256:'+hashlib.sha256(raw).hexdigest()==e['sha256'],e['path']
catalog=list(csv.DictReader(x for x in (sources/'targets.csv').read_text().splitlines() if x and not x.startswith('#')))
products={}
for line in (sources/'manifest.txt').read_text().splitlines():
    x=shlex.split(line)
    if x and x[0]=='curl':
        name=x[x.index('-o')+1];products[int(name.split('-')[2])]=name
population=[r for r in catalog if 8<=float(r['Tmag'])<=12 and int(r['TICID']) in products]
population.sort(key=lambda r:hashlib.sha256(('sj-tess-controls-v1:'+r['TICID']).encode()).hexdigest())
selected=[];screened=0
for r in population:
    tic=int(r['TICID']);p=Path('data/fits')/products[tic]
    if not p.exists():raise RuntimeError('Missing a source needed before the 100th eligible target: '+str(tic))
    screened+=1
    with fits.open(p,memmap=False) as h:
        radius=float(h[0].header.get('RADIUS') or np.nan);teff=float(h[0].header.get('TEFF') or np.nan);d=h[1].data
        valid=np.isfinite(d['TIME'])&np.isfinite(d['PDCSAP_FLUX'])&(d['QUALITY']==0)
        ok=.7<=radius<=1.5 and 4500<=teff<=6500 and valid.sum()>=10000 and np.ptp(d['TIME'][valid])>=20
        if ok:selected.append(tic)
    if len(selected)==100:break
selected.sort(key=lambda tic:hashlib.sha256(('sj-tess-split-v1:'+str(tic)).encode()).hexdigest())
actual=json.loads(Path('data/sample.json').read_text());assert selected==[r['tic'] for r in actual]
assert [r['split'] for r in actual]==['development']*40+['evaluation']*60
Path('results').mkdir(exist_ok=True)
Path('results/sampling.json').write_text(json.dumps({'source_digests_verified':len(external),'magnitude_eligible_count':len(population),'screened_count':screened,'selected_count':len(selected),'sample_and_split_reproduced':True},indent=2))
print('Sampling verified:',screened,'screened,',len(selected),'selected')
