"""Reproduce the chapter from fixed public teaching CSVs; Python standard library only."""
from pathlib import Path
import csv,json,math
ROOT=Path(__file__).resolve().parent
DATA=ROOT/"\uc2e4\uc81c\ub370\uc774\ud130"
def rows(name):
    with (DATA/name).open(encoding="utf-8-sig",newline="") as f:return list(csv.DictReader(f))
def save(name,result):
    (ROOT/name).write_text(json.dumps(result,ensure_ascii=False,indent=2)+"\n",encoding="utf-8")
    print(json.dumps(result,ensure_ascii=False,indent=2))

# Small centered degree-1/2 examples only: normal equations with partial pivoting.
# General applications should prefer a stable QR/SVD library. R uses lm (QR).
def fit(points,degree):
    k=degree+1
    a=[[sum(x**(i+j) for x,y in points) for j in range(k)]+[sum(y*x**i for x,y in points)] for i in range(k)]
    for c in range(k):
        pivot=max(range(c,k),key=lambda r:abs(a[r][c]));a[c],a[pivot]=a[pivot],a[c]
        scale=a[c][c]
        if abs(scale)<1e-12:raise ValueError("No unique fit")
        a[c]=[v/scale for v in a[c]]
        for r in range(k):
            if r!=c:
                q=a[r][c];a[r]=[v-q*w for v,w in zip(a[r],a[c])]
    return [r[-1] for r in a]
def predict(coeff,x):return sum(v*x**i for i,v in enumerate(coeff))
def score(coeff,points):
    e=[y-predict(coeff,x) for x,y in points]
    return dict(n=len(e),mae=sum(abs(v) for v in e)/len(e),rmse=math.sqrt(sum(v*v for v in e)/len(e)))
p=rows("penguins.csv")
points=[(float(r["flipper_length_mm"])-200,float(r["body_mass_g"])/1000) for r in p if r["flipper_length_mm"] and r["body_mass_g"]]
h=rows("korea-housing.csv")
hp=[((i-120)/4,float(r["nominal"])) for i,r in enumerate(h)]
result={}
for degree in [1,2]:
    pc=fit(points,degree)
    # Fit on earlier 160 only. Never use the later 20 here.
    hc=fit(hp[:160],degree)
    result[str(degree)]=dict(penguin_coefficients=pc,penguin=score(pc,points),
        housing_coefficients=hc,training=score(hc,hp[:160]),holdout=score(hc,hp[160:]),
        last_prediction=predict(hc,hp[-1][0]))
with (ROOT/"math05-housing-predictions.csv").open("w",encoding="utf-8",newline="") as f:
    w=csv.writer(f);w.writerow(["quarter","nominal","period","linear","quadratic"])
    for i,r in enumerate(h):w.writerow([r["quarter"],r["nominal"],"fit" if i<160 else "later",*[predict(result[str(d)]["housing_coefficients"],hp[i][0]) for d in [1,2]]])
save("math05-results.json",result)
