"""Reproduce the algebra/unit chapter with Python's standard library.
Uses the fixed 2026-10-20 teaching copy of public Palmer penguin data.
Run: python chapter01.py (CSV beside script, or inside 실제데이터).
"""
from pathlib import Path
import csv,json,hashlib,math
root=Path(__file__).resolve().parent
source=root/'penguins.csv'
if not source.exists():source=root/'실제데이터/penguins.csv'
with source.open(encoding='utf-8-sig',newline='') as f:rows=list(csv.DictReader(f))
def number(value):return None if value.strip()=='' else float(value)
for r in rows:
    r['row_id']=int(r['row_id'])
    for key in ('body_mass_g','flipper_length_mm'):r[key]=number(r[key])
observed=[r for r in rows if r['body_mass_g'] is not None]
complete=[r for r in observed if r['flipper_length_mm'] is not None]
first_five=[r['body_mass_g'] for r in rows[:5]]
actual=[v for v in first_five if v is not None]
mean_observed=sum(actual)/len(actual)
mean_zero=sum(v if v is not None else 0 for v in first_five)/len(first_five)
converted=[dict(row_id=r['row_id'],species=r['species'],mass_g=r['body_mass_g'],mass_kg=None if r['body_mass_g'] is None else r['body_mass_g']/1000) for r in rows]
for r in converted:
    if r['mass_g'] is not None:assert math.isclose(r['mass_kg']*1000,r['mass_g'],rel_tol=1e-12)
assert len(rows)==344 and len(observed)==342 and len(complete)==342
assert mean_observed==3562.5 and mean_zero==2850
assert rows[3]['body_mass_g'] is None
dest=root/'chapter01-results.csv'
with dest.open('w',encoding='utf-8-sig',newline='') as f:
    w=csv.DictWriter(f,fieldnames=['row_id','species','mass_g','mass_kg']);w.writeheader();w.writerows(converted)
print(json.dumps({'rows':len(rows),'observed_mass':len(observed),'complete_mass_flipper':len(complete),'first_five_observed_mean_g':mean_observed,'first_five_zero_filled_mean_g':mean_zero,'source_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),'saved':dest.name},ensure_ascii=False,indent=2))
