"""Independent 70-digit Decimal oracle, directly from editable official TSVs.
This is author verification, not official WHO runtime output or independent review.
"""
from pathlib import Path
from decimal import Decimal as Q,getcontext,ROUND_HALF_EVEN
import csv,json,datetime,hashlib
getcontext().prec=70
D=Path(__file__).resolve().parent
FILES={'underHeight':'anthro-lenanthro.txt','underBmi':'anthro-bmianthro.txt','olderHeight':'anthroplus-hfawho2007.txt','olderBmi':'anthroplus-bfawho2007.txt'}
tables={}
for mode,name in FILES.items():
 with (D/'source'/name).open() as f:tables[mode]={(r['sex'],int(r['age'])):tuple(Q(r[k]) for k in ['l','m','s']) for r in csv.DictReader(f,delimiter='\t')}
def param(mode,sex,days):
 if mode.startswith('under'):return tables[mode][sex,days]
 n=days*16;k=n//487;t=Q(n%487)/487
 return tuple(a+t*(b-a) for a,b in zip(tables[mode][sex,k],tables[mode][sex,k+1]))
def cut(z,p):
 l,m,s=p;return m*(1+l*s*z)**(1/l)
def inv(target,p,bmi):
 if not bmi or abs(target)<=3:return cut(target,p)
 if target>3:return cut(Q(3),p)+(target-3)*(cut(Q(3),p)-cut(Q(2),p))
 return cut(Q(-3),p)+(target+3)*(cut(Q(-2),p)-cut(Q(-3),p))
def evaluate(y,p,bmi):
 l,m,s=p;raw=((y/m)**l-1)/(l*s);fin=raw
 if bmi and raw>3:fin=3+(y-cut(Q(3),p))/(cut(Q(3),p)-cut(Q(2),p))
 if bmi and raw< -3:fin=-3+(y-cut(Q(-3),p))/(cut(Q(-2),p)-cut(Q(-3),p))
 return raw,fin
base=datetime.date(2020,1,1);fixtures=[]
for mode in FILES:
 bmi=mode.endswith('Bmi');dayss=[0,1,7,273,274,730,731,1826] if mode.startswith('under') else [1827,1828,2000,3287,4018,5844,6939,6970]
 for sex in ['1','2']:
  for days in dayss:
   p=param(mode,sex,days)
   for target in map(Q,['-7','-6.006','-6.004','-5.006','-5.004','-3.001','-3','-2.999','0','2.999','3','3.001','5.004','5.006','6.004','6.006','7']):
    y=inv(target,p,bmi)
    if y<Q('.001') or y>(1000 if bmi else 300):continue
    y=y.quantize(Q('.000000000001'))
    values=dict(mode=mode,sex=sex,posture='recumbent' if days<731 else 'standing',birthDate=base.isoformat(),measurementDate=(base+datetime.timedelta(days=days)).isoformat(),cm='100' if bmi else format(y,'f'))
    if bmi:values.update(kg=format(y,'f'),oedema='absent')
    raw,fin=evaluate(y,p,bmi);rounded=fin.quantize(Q('.01'),rounding=ROUND_HALF_EVEN)
    fixtures.append(dict(values=values,ageDays=days,lms=list(map(str,p)),measurementY=str(y),rawLMS=str(raw),finalScore=str(fin),rounded=str(rounded),qualityFlag=int(abs(rounded)>(5 if bmi else 6)),basis='Independent Decimal70 inversion plus recomputation from quantized visible measurement; exact TSV coefficient decimals.'))
# Published examples must use their exact monthly nodes, not substitute calendar ages.
published=[]
for month,bmi,pub in [(132,30,'3.35'),(192,14,'-3.80'),(108,19,'1.47')]:
 p=tables['olderBmi']['1',month];r,f=evaluate(Q(bmi),p,True)
 published.append(dict(months=month,bmi=bmi,lms=list(map(str,p)),raw=str(r),final=str(f),publishedTwoDecimal=pub,source='WHO2007 computation.pdf children1/2/3; printed intermediate values rounded. Exact dates cannot represent132 or108 fixed months; helper-only published-node check.'))
out=dict(precision=70,tableSource='Editable official TSV decimal text, not generated browser literal',officialRuntimeExecuted=False,fixtures=fixtures,publishedExamples=published)
(D/'oracle-fixtures.json').write_text(json.dumps(out,indent=2)+'\n')
(D/'evidence/oracle-generation-receipt.json').write_text(json.dumps(dict(cases=len(fixtures),publishedExamples=len(published),precision=70,sha256=hashlib.sha256((D/'oracle-fixtures.json').read_bytes()).hexdigest()),indent=2)+'\n')
print('Decimal70 cases',len(fixtures),'published examples',len(published))
