"""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))

h=rows("korea-housing.csv")
a=next(i for i,r in enumerate(h) if r["quarter"]=="2010-Q1")
b=next(i for i,r in enumerate(h) if r["quarter"]=="2024-Q4")
start,end=float(h[a]["nominal"]),float(h[b]["nominal"])
intervals=b-a;years=intervals/4;ratio=end/start
annual=math.expm1(math.log(ratio)/years)
logs=[math.log(float(h[i]["nominal"])/float(h[i-1]["nominal"])) for i in range(a+1,b+1)]
wb=[r for r in rows("worldbank.csv") if r["country"]=="KOR"]
first,last=wb[0],wb[-1]
gdp_ratio=float(last["gdp_pc"])/float(first["gdp_pc"])
gdp_years=int(last["year"])-int(first["year"])
result=dict(housing_observations=b-a+1,housing_intervals=intervals,housing_years=years,
    housing_ratio=ratio,housing_quarter_rate=math.expm1(math.log(ratio)/intervals),
    housing_annual_rate=annual,housing_log_change=math.log(ratio),
    housing_sum_log_changes=sum(logs),last_quarter_log_change=logs[-1],
    conditional_doubling_years=math.log(2)/math.log1p(annual),
    gdp_observations=len(wb),gdp_years=gdp_years,gdp_start=float(first["gdp_pc"]),
    gdp_end=float(last["gdp_pc"]),gdp_ratio=gdp_ratio,
    gdp_annual_rate=math.expm1(math.log(gdp_ratio)/gdp_years),
    gdp_unit="constant 2015 US dollars per person")
# Small numerical discrepancy can occur because floating point arithmetic is finite.
assert math.isclose(result["housing_log_change"],sum(logs),abs_tol=1e-12)
save("math06-results.json",result)
