"""Independent Decimal/Fraction author oracle; no JavaScript or archived R execution.
Inputs are finite 12-place decimal records; expected values use THOSE tokens.
"""
from pathlib import Path
from decimal import Decimal as D,localcontext,ROUND_HALF_EVEN
from fractions import Fraction as F
from datetime import date,timedelta
import json
P=Path(__file__).resolve().parent
spec={'underHeight':('growthstandards_lenanthro',[0,273,274,730,731,1826]),'underBmi':('growthstandards_bmianthro',[0,273,274,730,731,1826]),'olderHeight':('hfa_growth_standards',[1827,2000,3682,6970]),'olderBmi':('bfa_growth_standards',[1827,2000,3682,6970]),'underWeight':('growthstandards_weianthro',[0,273,274,730,731,1826]),'olderWeight':('wfa_growth_standards',[1827,2000,3682])}
tables={key:json.loads((P/'data'/(key+'.json')).read_text())['rows']for key,_ in spec.values()}
with localcontext()as ctx:
 ctx.prec=90
 pi=D('3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117')
 def cdf(z):
  term=z;total=z
  for n in range(1,150):term=-term*z*z*D(2*n-1)/D(2*n*(2*n+1));total+=term
  return D('.5')+total/(2*pi).sqrt()
 def coeff(key,sex,day):
  rr={r['age']:r for r in tables[key]if r['sex']==sex}
  if day<=1826:return [D(str(rr[day][k]))for k in ['l','m','s']]
  mo=F(day*16,487);k=mo.numerator//mo.denominator;t=D(mo.numerator%mo.denominator)/D(mo.denominator)
  return [D(str(rr[k][n]))+t*(D(str(rr[k+1][n]))-D(str(rr[k][n])))for n in ['l','m','s']]
 fixtures=[]
 for mode,(key,days)in spec.items():
  adjusted=not mode.endswith('Height')
  for sex in [1,2]:
   for day in days:
    l,m,s=coeff(key,sex,day)
    def cut(z):return m*((1+l*s*z).ln()/l).exp()if l else m*(s*z).exp()
    for target in ['-6.006','-6.004','-3.0001','-3','-2','-0.000000001','0','0.000000001','1','2','3','3.0001','5.004','5.006']:
     target=D(target)
     y=(cut(D(3))+(target-3)*(cut(D(3))-cut(D(2)))if adjusted and target>3 else cut(D(-3))+(target+3)*(cut(D(-2))-cut(D(-3)))if adjusted and target< -3 else cut(target))
     token=format(y.quantize(D('0.000000000001')),'f');y=D(token)
     if y<D('.001')or y>(300 if mode.endswith('Height')else 1000):continue
     raw=(y-m)/(m*s)if l==1 else((l*(y/m).ln()).exp()-1)/(l*s)if l else(y/m).ln()/s
     final=(3+(y-cut(D(3)))/(cut(D(3))-cut(D(2)))if raw>3 else -3+(y-cut(D(-3)))/(cut(D(-2))-cut(D(-3)))if raw< -3 else raw)if adjusted else raw
     rounded=final.quantize(D('.01'),rounding=ROUND_HALF_EVEN)
     values={'mode':mode,'sex':str(sex),'birthDate':'2020-01-01','measurementDate':(date(2020,1,1)+timedelta(days=day)).isoformat(),'posture':'recumbent'if day<731 else'standing','cm':token if mode.endswith('Height')else'100','kg':token,'oedema':'absent','outputComparison':'scoreAndPercentile','recordedTableConfirmed':'confirmed','referenceContext':'termChronological'}
     # Rounding a mathematical inverse cut to12decimal places does not make it an
     # exact cut. Only L1 exact rational boundaries can be established as such.
     central=abs(raw)<=3 if mode.endswith('Height') else abs(raw)<D('2.9999999999')
     if mode.endswith('Height')and raw in [D(-3),D(3)]:central=True
     flag=rounded< -6 or rounded>5 if mode.endswith('Weight') else abs(rounded)>(6 if mode.endswith('Height') else 5)
     fixtures.append({'values':values,'days':day,'coefficients':list(map(str,[l,m,s])),'raw':str(raw),'final':str(final),'twoPlaceDecimalOracle':str(rounded),'flag':int(flag),'centralEligible':central,'percentile':str(100*cdf(raw))if central else None,'constructedNotPublished':True})
 known=[{'z':str(D(i)/1000),'probability':str(cdf(D(i)/1000))}for i in range(-3000,3001)]
 out={'status':'Original high-precision author oracle, requires independent review','precisionDigits':90,'fixtures':fixtures,'cdfGrid':known,'noWHO_R_orJavaScriptExecuted':True,'limits':'Expected values use actual12-place inputs; Decimal mathematical round ties and binary64 source rounding are distinguished in tests.'}
(P/'r5-oracle-fixtures.json').write_text(json.dumps(out,separators=(',',':'))+'\n')
print(json.dumps({'r5DecimalRecords':len(fixtures),'cdfGrid':len(known)}))
