"""MATH-20. Reproduce constrained descriptive fits from actual public CSVs.
Constraints are teaching assumptions, not observed policies or business plans.
"""
from pathlib import Path
from fractions import Fraction as Q
import csv,json
root=Path(__file__).resolve().parent
def rows(f):
    with(root/f).open(encoding='utf-8-sig',newline='')as h:return list(csv.DictReader(h))
C=rows('math15-sources/korea-2014-2024-gdp-linear-projection.csv')
u=[Q(r['centered_year_u'])for r in C];y=[Q(r['reported_GDPpc_constant2015USD_per_person'])for r in C];n=len(y);a=sum(y)/n;b=sum(v*w for v,w in zip(u,y))/sum(v*v for v in u);A=y[5]
lossC=sum((A+b*v-w)**2 for v,w in zip(u,y))/(2*n);lam=a-A
P=rows('math10-sources/power-2006-12-17.csv');p1=[Q(r['Sub_metering_1'])for r in P];p2=[Q(r['Sub_metering_2'])for r in P];mu1=sum(p1)/len(p1);mu2=sum(p2)/len(p2);B=Q(3);p=(B+mu1-mu2)/2;q=B-p;lamP=(mu1+mu2-B)/2
floor=sum((v-mu1)**2+(w-mu2)**2 for v,w in zip(p1,p2))/(2*len(p1));lossP=floor+((p-mu1)**2+(q-mu2)**2)/2
Arows=rows('math16-sources/apple-sales-two-year-gram-input.csv');x=[Q(r['reported_FY2023_net_sales_million_USD'])for r in Arows];z=[Q(r['reported_FY2024_net_sales_million_USD'])for r in Arows];xx=sum(v*v for v in x);xz=sum(v*w for v,w in zip(x,z));alpha=xz/xx;cap=Q(101,100);grad=(xx*cap-xz)/len(x);lossA=sum((cap*v-w)**2 for v,w in zip(x,z))/(2*len(x))
assert p>0 and q>0 and p-mu1+lamP==0 and q-mu2+lamP==0 and grad<0
results=dict(country_n=n,country_a0=a,country_b=b,country_anchor=A,country_lambda=lam,country_loss=lossC,household_n=len(p1),household_mu1=mu1,household_mu2=mu2,household_threshold=mu2-mu1,household_B3_a=p,household_B3_b=q,household_B3_lambda=lamP,household_B3_loss=lossP,company_alpha0=alpha,company_cap=cap,company_nu_upper=-grad,company_loss=lossA)
(root/'math20-results.json').write_text(json.dumps({k:float(v)for k,v in results.items()},indent=2)+'\n',encoding='utf-8')
print('MATH-20: exact-rational KKT reproduction from 11/1440/5 actual input records passed.')
