"""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))

p=rows("penguins.csv")
paired=[r for r in p if r["flipper_length_mm"] and r["body_mass_g"]]
same=[r for r in paired if float(r["flipper_length_mm"])==181]
outputs=sorted({float(r["body_mass_g"])/1000 for r in same})
# Checking every observed input is different from checking one input.
length_to_mass={}
for r in paired:length_to_mass.setdefault(float(r["flipper_length_mm"]),set()).add(float(r["body_mass_g"])/1000)
first=[r for r in paired if int(r["row_id"])<=3]
x1,x2=[float(r["flipper_length_mm"]) for r in first[:2]]
y1,y2=[float(r["body_mass_g"])/1000 for r in first[:2]]
slope=(y2-y1)/(x2-x1);intercept=y1-slope*x1
result=dict(complete_pairs=len(paired),missing_pairs=len(p)-len(paired),
    same_length_rows=[int(r["row_id"]) for r in same],distinct_outputs=outputs,
    distinct_output_count=len(outputs),observed_length_relation_is_function=all(len(v)==1 for v in length_to_mass.values()),
    first_two_slope=slope,first_two_intercept=intercept,
    third_prediction=intercept+slope*float(first[2]["flipper_length_mm"]),
    reciprocal_at_180=None,sqrt_at_170=0,kg_at_3750=3750/1000)
save("math04-results.json",result)
