#!/usr/bin/env python3
"""Reproduce generated parallax teaching cases offline. Python 3.9+, standard library.
Not a Gaia catalogue analysis or a fit to telescope observations.
"""
import argparse,csv,hashlib,json,math,sys
from pathlib import Path
AU_METERS=149597870700
AU_PER_PC=648000/math.pi
CASES=[('A',5),('B',10),('C',20),('D',100)]
PHASES=[0,90,180,270,360]
SOURCES=['https://syrte.obspm.fr/IAU_resolutions/Sumredef_au.html','https://arxiv.org/pdf/1510.06262']
def require(test,message):
    if not test:raise ValueError(message)
def analyze(folder):
    ref=folder/'unit-reference.csv';data=folder/'simulated-parallax-cases.csv'
    refs=list(csv.DictReader(ref.open(newline='',encoding='utf-8')))
    require(len(refs)==2,'Expected two unit-definition rows')
    for row,quantity,definition,unit,source in zip(refs,['astronomical_unit','parsec'],['149597870700','648000/pi'],['m','au'],SOURCES):
        require(row==dict(quantity=quantity,exact_definition=definition,unit=unit,source_url=source),'Unit-reference transcription mismatch')
    rows=list(csv.DictReader(data.open(newline='',encoding='utf-8')))
    require(len(rows)==20,'Expected twenty generated position rows')
    results=[]
    for i,(case_id,distance) in enumerate(CASES):
        p=math.atan(1/(distance*AU_PER_PC))*AU_PER_PC;epochs=[]
        for j,phase in enumerate(PHASES):
            row=rows[i*5+j]
            require(row['case_id']==case_id and float(row['nominal_distance_pc'])==distance and float(row['phase_deg'])==phase,'Case or epoch identity mismatch')
            x=float(row['simulated_x_arcsec']);y=float(row['simulated_y_arcsec'])
            expected=(-p*math.cos(math.radians(phase)),-p*math.sin(math.radians(phase)))
            require(all(math.isfinite(a) and abs(a-b)<=5.01e-13 for a,b in zip([x,y],expected)),'Generated position mismatch')
            epochs.append(dict(phaseDeg=phase,months=phase/30,xArcsec=x,yArcsec=y))
        shift=math.hypot(epochs[2]['xArcsec']-epochs[0]['xArcsec'],epochs[2]['yArcsec']-epochs[0]['yArcsec']);half=shift/2
        exact_inverse=1/(math.tan(half/AU_PER_PC)*AU_PER_PC)
        require(abs(exact_inverse-distance)<1e-7,'Exact inverse failed')
        require(abs(math.hypot(epochs[4]['xArcsec']-epochs[0]['xArcsec'],epochs[4]['yArcsec']-epochs[0]['yArcsec']))<1e-12,'One-year track does not close')
        results.append(dict(case=case_id,nominalDistancePc=distance,parallaxArcsec=p,parallaxMas=p*1000,sixMonthDisplacementArcsec=shift,recoveredParallaxArcsec=half,smallAngleDistancePc=1/half,exactRecoveredDistancePc=exact_inverse,wrongFullShiftDistancePc=1/shift,lightYears=distance*AU_PER_PC*AU_METERS/(299792458*365.25*86400),epochs=epochs))
    b=results[1]
    return dict(methodVersion='1.0',resourceRelease='265',activity='https://darksciencedocs.com/light-lab/parallax/',provenance='Two published unit definitions; four fictional stationary stars and twenty positions generated by the existing parallax model. No observed astrometry or Gaia catalogue rows.',sourceReviewDate='2026-10-25',constants=dict(auMeters=AU_METERS,auPerParsec=AU_PER_PC,arcsecPerRadian=AU_PER_PC,milliarcsecPerArcsec=1000,julianYearDays=365.25),cases=results,magnificationCheck=dict(case='B',zoomFactors=[1,5,20],renderedRadiusSvgUnits=[b['parallaxArcsec']*170*z for z in [1,5,20]],physicalParallaxArcsec=b['parallaxArcsec']),checks=dict(referenceSha256=hashlib.sha256(ref.read_bytes()).hexdigest(),generatedCasesSha256=hashlib.sha256(data.read_bytes()).hexdigest(),allForwardInverseAndClosureChecks=True),limits='Circular 1-au orbit, ecliptic-pole target, stationary fictional stars and infinitely distant background. No proper motion, finite-background correction, orbit eccentricity, calibration or noise. The exact inverse is exact for this ideal geometry only. Stored digits are not measurement precision; naive inversion of uncertain measured parallax is not generally reliable.')
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())
