"""Reproduce MATH-11 from the fixed teaching CSV. Python standard library only."""
from pathlib import Path
import csv,json,math
from decimal import Decimal,localcontext
root=Path(__file__).resolve().parent
with (root/'math11-sources/korea-2014-2024-observed-model-taylor-errors.csv').open(encoding='utf-8-sig',newline='') as f:
    source=list(csv.DictReader(f))
cases=json.loads((root/'taylor-cases.json').read_text(encoding='utf-8'));m=cases['models']['growth']
def poly(x,n):return sum(x**j/math.factorial(j) for j in range(n+1))
results={}
rows=[]
for x in [-2,-1,0,.2,1,2]:
    for n in [0,1,2,6,12]:
        exact=math.exp(x);p=poly(x,n);bound=math.exp(max(0,x))*abs(x)**(n+1)/math.factorial(n+1)
        rows.append(dict(x=x,degree=n,exact=exact,polynomial=p,signed_error=exact-p,lagrange_bound=bound))
        if n in [1,2,6]:results[f'exp_{x:g}_n{n}']=p
for x in [1,4,4.4,7]:
    h=x-4;results[f'sqrt_{x:g}']=2+h/4-h*h/64
for x in [-.9,-.5,.5,.9]:
    for n in [5,20]:results[f'log_{x:g}_n{n}']=sum((-1)**(j+1)*x**j/j for j in range(1,n+1))
with localcontext() as ctx:
    ctx.prec=60;A=Decimal(str(m['baseValue']));k=Decimal(m['kDecimal'])
    for year in [2014,2020,2024]:
        h=Decimal(year-2014);exact=A*(k*h).exp();t1=A*(1+k*h);t2=t1+A*k*k*h*h/2
        for name,value in [('exact',exact),('linear',t1),('quadratic',t2),('bound',exact*(k*h)**3/6)]:
            results[f'gdp_{year}_{name}']=float(value)
    results['gdp_2020_residual']=float(Decimal('33215.92989281')-A*(k*6).exp())
with (root/'math11-comparison.csv').open('w',encoding='utf-8',newline='') as f:
    w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
(root/'math11-results.json').write_text(json.dumps(results,indent=2)+'\n',encoding='utf-8')
print('MATH-11:',len(source),'source years;',len(results),'reproduced quantities')
