#!/usr/bin/env python3
"""Offline sodium-doublet teaching calculation. Python 3.9+, standard library.
Run: python3 verify_analysis.py --data-dir .
Published reference wavelengths; SIMULATED profiles, not telescope measurements.
"""
import argparse, csv, hashlib, json, math, sys
from pathlib import Path

FWHM_FACTOR=2.3548200450309493
INTRINSIC_SIGMA_NM=0.08
CONTRAST=0.8
SOURCE='https://physics.nist.gov/PhysRefData/Handbook/Tables/sodiumtable3_a.htm'

def require(condition,message):
    if not condition: raise ValueError(message)

def intensity(wavelength,resolution,lines):
    total=0.0
    for line in lines:
        center=float(line['air_nm']);strength=float(line['illustrative_strength'])
        sigma=math.hypot(INTRINSIC_SIGMA_NM,center/resolution/FWHM_FACTOR)
        q=(wavelength-center)/sigma
        if abs(q)<=8:
            total+=CONTRAST*strength*0.2/(math.sqrt(2*math.pi)*sigma)*math.exp(-0.5*q*q)
    return total

def analyze(folder):
    reference_path=folder/'sodium-reference.csv'
    lines=list(csv.DictReader(reference_path.open(newline='',encoding='utf-8')))
    require(len(lines)==2,'Expected exactly two sodium references')
    for row,feature,angstrom,nm,strength in zip(lines,['D2','D1'],[5889.950,5895.924],[588.9950,589.5924],[1.0,0.65]):
        require(row['feature']==feature and float(row['source_air_angstrom'])==angstrom and float(row['air_nm'])==nm and float(row['illustrative_strength'])==strength and row['source_url']==SOURCE,'Reference or teaching-strength mismatch')
        require(abs(float(row['source_air_angstrom'])/10-float(row['air_nm']))<1e-12,'Angstrom-to-nanometer conversion mismatch')
    profiles_path=folder/'simulated-sodium-profiles.csv'
    profiles=list(csv.DictReader(profiles_path.open(newline='',encoding='utf-8')))
    require(len(profiles)==1601,'Expected 1,601 simulated wavelength samples')
    curves={400:[],6000:[]}
    for i,row in enumerate(profiles):
        wavelength=float(row['air_wavelength_nm'])
        require(abs(wavelength-(585+i*0.005))<1e-12,'Profile wavelength grid mismatch')
        for resolution in curves:
            predicted=intensity(wavelength,resolution,lines)
            require(abs(float(row['simulated_intensity_R'+str(resolution)])-predicted)<=5.01e-13,'Simulated intensity mismatch at row '+str(i+1))
            curves[resolution].append((wavelength,predicted))
    first,second=[float(row['air_nm']) for row in lines]
    spacing=second-first;midpoint=(first+second)/2
    settings=[]
    for resolution,curve in curves.items():
        area=sum((b[0]-a[0])*(a[1]+b[1])/2 for a,b in zip(curve,curve[1:]))
        maxima=[curve[i][0] for i in range(1,len(curve)-1) if curve[i][1]>curve[i-1][1] and curve[i][1]>curve[i+1][1]]
        settings.append({'resolvingPower':resolution,'instrumentFwhmAtMidpointNm':midpoint/resolution,
            'combinedFwhmAtMidpointNm':FWHM_FACTOR*math.hypot(INTRINSIC_SIGMA_NM,midpoint/resolution/FWHM_FACTOR),
            'sampledMaximaNm':maxima,'integratedSimulatedEmission585To593':area})
    return {'methodVersion':'1.0','resourceRelease':'262',
        'activity':'https://darksciencedocs.com/light-lab/spectroscopy/',
        'referenceSource':SOURCE,'sourceReviewDate':'2026-10-25',
        'provenance':'Published NIST air wavelengths; synthetic Gaussian teaching profiles. Not observed stellar or laboratory intensity data.',
        'sodiumAirWavelengthsNm':[first,second],'separationNm':spacing,'midpointNm':midpoint,
        'spacingComparisonResolvingPower':midpoint/spacing,
        'assumptions':{'intrinsicSigmaNm':INTRINSIC_SIGMA_NM,'contrast':CONTRAST,'illustrativeStrengths':[1,0.65],'gaussianFwhmFactor':FWHM_FACTOR},
        'settings':settings,'analyticTotalSimulatedEmission':CONTRAST*0.2*(1+0.65),
        'grid':{'startNm':585,'endNm':593,'stepNm':0.005,'rows':len(profiles)},
        'checks':{'referenceCsvSha256':hashlib.sha256(reference_path.read_bytes()).hexdigest(),'simulatedProfilesSha256':hashlib.sha256(profiles_path.read_bytes()).hexdigest(),'allSimulatedSamplesMatch':True},
        'limits':'R about 986 compares instrumental FWHM with line spacing, not a universal detection threshold. Intrinsic widths, line strengths, noise, sampling and response matter. No abundance, real stellar composition or distance is measured. Chart normalization changes between presets.'}

def main():
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--data-dir',type=Path,default=Path('.'));args=parser.parse_args()
    try: print(json.dumps(analyze(args.data_dir),indent=2,allow_nan=False))
    except (OSError,ValueError,KeyError) as error:
        print('Verification failed: '+str(error),file=sys.stderr);return 1
    return 0

if __name__=='__main__': sys.exit(main())
