#!/usr/bin/env python3
"""Offline radial-Doppler teaching analysis. Python 3.9+, standard library.
Run: python3 verify_analysis.py --data-dir .
The cases are generated model values, not telescope observations.
"""
import argparse,csv,hashlib,json,math,sys
from pathlib import Path
C_KMS=299792.458
SOURCE='https://classic.sdss.org/dr4/products/spectra/vacwavelength.php'
CASES=[('A',0),('B',3000),('C',-3000),('D',60000)]
def require(test,message):
    if not test: raise ValueError(message)
def analyze(folder):
    reference=folder/'vacuum-reference.csv';cases_file=folder/'simulated-shift-cases.csv'
    refs=list(csv.DictReader(reference.open(newline='',encoding='utf-8')))
    require(len(refs)==2,'Expected two reference rows')
    for row,line,angstrom,rounded in zip(refs,['Hbeta','Halpha'],[4862.721,6564.614],[486.3,656.5]):
        require(row['line']==line and float(row['source_vacuum_angstrom'])==angstrom and float(row['teaching_rest_nm'])==rounded and row['source_url']==SOURCE,'Reference transcription mismatch')
        require(round(angstrom/10,1)==rounded,'Vacuum conversion/rounding mismatch')
    records=list(csv.DictReader(cases_file.open(newline='',encoding='utf-8')))
    require(len(records)==8,'Expected eight generated line rows')
    results=[]
    for index,(case_id,nominal_velocity) in enumerate(CASES):
        ratio=math.sqrt((1+nominal_velocity/C_KMS)/(1-nominal_velocity/C_KMS));lines=[]
        for j,ref in enumerate(refs):
            row=records[index*2+j];rest=float(ref['teaching_rest_nm']);received=float(row['simulated_received_nm'])
            require(row['case_id']==case_id and row['line']==ref['line'] and float(row['teaching_rest_nm'])==rest,'Case identity/reference mismatch')
            require(math.isfinite(received) and abs(received-rest*ratio)<=5.01e-13,'Simulated wavelength mismatch')
            q=received/rest;z=q-1;speed=C_KMS*(q*q-1)/(q*q+1)
            lines.append({'line':row['line'],'restNm':rest,'receivedNm':received,'shiftNm':received-rest,'wavelengthRatio':q,'z':z,'recoveredRadialVelocityKms':speed})
        require(abs(lines[0]['wavelengthRatio']-lines[1]['wavelengthRatio'])<1e-12,'The pattern does not share one factor')
        require(all(abs(line['recoveredRadialVelocityKms']-nominal_velocity)<1e-6 for line in lines),'Inverse velocity failed')
        z=ratio-1
        results.append({'case':case_id,'nominalVelocityKms':nominal_velocity,'nominalVelocityMilesPerSecond':nominal_velocity/1.609344,'direction':'receding' if nominal_velocity>0 else 'approaching' if nominal_velocity<0 else 'at rest','wavelengthRatio':ratio,'z':z,'frequencyRatio':1/ratio,'lowSpeedApproximationCzKms':C_KMS*z,'approximationErrorKms':C_KMS*z-nominal_velocity,'lines':lines})
    return {'methodVersion':'1.0','resourceRelease':'264','activity':'https://darksciencedocs.com/light-lab/redshift-blueshift/',
        'provenance':'Rounded vacuum references informed by SDSS; cases generated by the existing radial teaching model. Not measured spectra or a cosmological distance calculation.',
        'speedOfLightKms':C_KMS,'referenceSource':SOURCE,'sourceReviewDate':'2026-10-25','cases':results,
        'checks':{'referenceSha256':hashlib.sha256(reference.read_bytes()).hexdigest(),'generatedCasesSha256':hashlib.sha256(cases_file.read_bytes()).hexdigest(),'allCasesMatchForwardAndInverse':True},
        'limits':'Pure radial inertial motion in flat spacetime. Rounded rest references and generated wavelengths do not establish real measurement precision. No transverse/gravitational/cosmological shifts, instrument noise, calibration errors, beaming or distance inference.'}
def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--data-dir',type=Path,default=Path('.'));args=p.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())
