#!/usr/bin/env python3
"""Create complete ML22 chart coordinates and optional original vectors.
Input: outputs of reproduce-wine-churn-comparison.py. No source model or answer
lookup; all coordinates derive from the supplied exact comparison CSVs.
--coordinates-only requires only Python standard library. Full plotting also
requires Matplotlib and a Korean-capable font (e.g.MalgunGothic on Windows).
The CSV xExact/yExact fields refer to exact values from Python Fraction exports.
R approximate exports are deliberately not accepted as exact input here.
"""
from pathlib import Path
from fractions import Fraction as F
import argparse,csv,json,hashlib,textwrap
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--input-dir',type=Path,required=True);parser.add_argument('--output-dir',type=Path,required=True);parser.add_argument('--coordinates-only',action='store_true');args=parser.parse_args();P=args.input_dir;S=args.output_dir
if S.exists()and any(S.iterdir()):parser.error('Preserve outputs: output-dir must be new or empty')
S.mkdir(parents=True,exist_ok=True)
read=lambda p:list(csv.DictReader(p.open(encoding='utf8',newline='')))
C=lambda ko,en:dict(ko=ko,en=en)
for row in read(P/'candidate-selection.csv'):
 if row['validationRiskExact']=='':parser.error('Use exact Python comparison outputs; R approximations are not exact chart inputs')

metrics=read(P/'benchmark-metrics.csv');pairs=read(P/'paired-test-losses.csv');ledger=read(P/'complete-prediction-ledger.csv');selection=read(P/'candidate-selection.csv');data={};titles={'country':C('포르투갈 와인 기록','Portuguese wine records'),'person':C('NLS 개인 로그 임금','NLS individual log wages'),'company':C('통신 고객 이탈','Telecom churn')}
COHORT_LABELS={'red': {'ko': '적포도주', 'en': 'Red wine'}, 'white': {'ko': '백포도주', 'en': 'White wine'}, 'schooling-at-most12': {'ko': '교육 12년 이하', 'en': 'Schooling at most 12'}, 'schooling-over12': {'ko': '교육 12년 초과', 'en': 'Schooling above 12'}, 'pay-as-you-go': {'ko': '종량제', 'en': 'Pay-as-you-go'}, 'contractual': {'ko': '계약제', 'en': 'Contractual'}}
def pt(ID,x,y):return dict(id=ID,x=None if x in[None,'']else float(F(str(x))),y=None if y in[None,'']else float(F(str(y))),xExact=None if x in[None,'']else str(x),yExact=None if y in[None,'']else str(y))
for kind in ['country','person','company']:
 title=titles[kind];rr=[r for r in pairs if r['dataset']==kind];cohorts=list(dict.fromkeys(r['cohort']for r in rr));unit=C('품질 점수'if kind=='country'else'원 로그 임금 · 로그 점'if kind=='person'else'이탈 점수 0–1','Quality-score units'if kind=='country'else'Native log hourly-wage units'if kind=='person'else'Churn score 0–1');lossunit=C('품질 점수의 제곱'if kind=='country'else'로그 점의 제곱'if kind=='person'else'Brier · 한 성분','Squared quality-score units'if kind=='country'else'Squared log units'if kind=='person'else'One-component Brier loss');charts=[]
 charts.append(dict(id=kind+'-observed-predicted',type='scatter',title=C(title['ko']+' · 실제값과 두 예측',title['en']+': observed versus predicted'),xLabel=C('원 관측 결과','Native observed outcome'),yLabel=unit,note=C('같은 시험 원행만 비교 · 라벨 결측은 0점으로 그리지 않음','Same planned test records; missing labels are not invented zero points'),series=[dict(label=C('검증 선택 릿지','Validation-selected ridge'),data=[pt(r['id'],r['y'],r['selectedPrediction'])for r in rr]),dict(label=C('훈련 평균 상수','Training-mean constant'),data=[pt(r['id'],r['y'],r['baselinePrediction'])for r in rr])]))
 indices={r['id']:i+1 for i,r in enumerate([x for x in ledger if x['dataset']==kind])};charts.append(dict(id=kind+'-paired-differences',type='scatter',title=C(title['ko']+' · 같은 행의 손실 차이',title['en']+': same-record loss differences'),xLabel=C('원행 순서 · 달력 시간 아님','Original source order, not calendar time'),yLabel=C('선택 손실 − 상수 손실','Selected loss minus constant loss'),note=C('음수는 선택 모형 손실이 더 작음 · 인과 효과·신뢰구간 아님','Negative favors the selected model; not a causal effect or confidence interval'),series=[dict(label=C('쌍별 손실 차이','Paired loss difference'),data=[pt(r['id'],indices[r['id']],r['difference'])for r in rr])]))
 selected=[r for r in selection if r['dataset']==kind];names=[r['candidate']for r in selected];charts.append(dict(id=kind+'-candidate-risks',type='points',title=C(title['ko']+' · 사전 후보의 검증·시험 위험',title['en']+': validation and test risks'),xLabel=C('1 상수 · 2 λ=.01 · 3 λ=.1 · 4 λ=1 · 5 한 단계 나무','1 constant; 2 λ=.01; 3 λ=.1; 4 λ=1; 5 stump'),yLabel=lossunit,note=C('검증이 후보를 고른 뒤 시험을 보고함 · 시험 재선택 아님','Validation selects first; test results report performance without reopening selection'),xTicks=[1,2,3,4,5],series=[dict(label=C('검증 MSE','Validation MSE'),data=[pt(r['candidate'],i+1,r['validationRiskExact'])for i,r in enumerate(selected)]),dict(label=C('시험 MSE','Test MSE'),data=[pt(r['candidate'],i+1,r['testMSEExact'])for i,r in enumerate(selected)])]))
 lookup={(r['candidate'],r['cohort']):r['exact']for r in metrics if r['dataset']==kind and r['role']=='test'and r['metric']=='MSE'};charts.append(dict(id=kind+'-cohort-risks',type='points',title=C(title['ko']+' · 두 코호트의 시험 위험',title['en']+': test risks within cohorts'),xLabel=C('코호트 위치 · 원 이름은 범례·수치표','Cohort positions; native names in numeric table'),yLabel=lossunit,note=C('각 코호트의 양의 완전 평가 집합 · 관측 집단 차이는 인과 설명 아님','Positive complete evaluation frames; cohort differences do not identify causes'),xTicks=list(range(1,len(cohorts)+1)),xTickLabels={lang:[COHORT_LABELS[g][lang]for g in cohorts]for lang in ['ko','en']},cohortIDs=cohorts,series=[dict(label=C('검증 선택 릿지','Validation-selected ridge'),data=[pt(g,i+1,lookup['ridge:1/100',g])for i,g in enumerate(cohorts)]),dict(label=C('훈련 평균 상수','Training-mean constant'),data=[pt(g,i+1,lookup['constant',g])for i,g in enumerate(cohorts)])]))
 data[kind]=dict(charts=charts,unit=unit,lossUnit=lossunit,cohorts=cohorts,originalObservationUnit=C('와인 기록 · 국가 행 아님'if kind=='country'else'NLS 원 개인 기록'if kind=='person'else'원 통신 고객 기록','Wine record, not a country'if kind=='country'else'Original NLS individual record'if kind=='person'else'Native telecom customer record'))


(S/'source-figure-data.json').write_text(json.dumps(data,ensure_ascii=False,separators=(',',':'))+'\n',encoding='utf8')
coordinate_rows=[]
for kind,d in data.items():
 for chart in d['charts']:
  for series_index,series in enumerate(chart['series']):
   for point in series['data']:coordinate_rows.append(dict(dataset=kind,chart=chart['id'],series=series_index,id=point['id'],xExact=''if point['xExact']is None else point['xExact'],yExact=''if point['yExact']is None else point['yExact'],xApprox=''if point['x']is None else format(point['x'],'.17g'),yApprox=''if point['y']is None else format(point['y'],'.17g'),defined=str(point['x']is not None and point['y']is not None).lower()))
with(S/'source-chart-coordinates.csv').open('w',encoding='utf8',newline='')as f:
 writer=csv.DictWriter(f,fieldnames=['dataset','chart','series','id','xExact','yExact','xApprox','yApprox','defined'],lineterminator='\n');writer.writeheader();writer.writerows(coordinate_rows)
if not args.coordinates_only:
 import matplotlib
 matplotlib.use('Agg')
 import matplotlib.pyplot as plt
 from matplotlib import ticker
 G=S/'figures';G.mkdir()
 plt.rcParams.update({'font.family':['Malgun Gothic','Arial'],'font.size':13,'svg.fonttype':'none','axes.unicode_minus':False});files=[];colors=['#0f766e','#b45309','#4f46e5']
 for kind,d in data.items():
  for chart in d['charts']:
   for lang in ['ko','en']:
    fig,ax=plt.subplots(figsize=(12,6.7),dpi=100);fig.subplots_adjust(left=.12,right=.97,bottom=.28,top=.76);ax.set_title(chart['title'][lang],loc='left',fontsize=16,pad=50);ax.grid(axis='y',color='#dbe5ec',linewidth=.7);ax.set_axisbelow(True)
    for j,series in enumerate(chart['series']):
     points=[p for p in series['data']if p['x']is not None and p['y']is not None];ax.scatter([p['x']for p in points],[p['y']for p in points],s=48 if chart['type']=='points'else 13,alpha=.78 if chart['type']=='points'else .5,color=colors[j],label=series['label'][lang],zorder=3)
    if 'xTicks'in chart:
     labels=chart.get('xTickLabels',[str(x)for x in chart['xTicks']]);labels=labels[lang]if isinstance(labels,dict)else labels;ax.set_xticks(chart['xTicks'],labels)
     if 'xTickLabels'in chart:
      ticks=ax.get_xticklabels()
      if ticks:ticks[0].set_horizontalalignment('left');ticks[-1].set_horizontalalignment('right')
    else:ax.xaxis.set_major_locator(ticker.MaxNLocator(nbins=5))
    ax.yaxis.set_major_locator(ticker.MaxNLocator(nbins=5));ax.ticklabel_format(axis='y',style='plain',useOffset=False);ax.set_xlabel(chart['xLabel'][lang],labelpad=13);ax.set_ylabel(chart['yLabel'][lang],labelpad=10);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),ncol=len(chart['series']),frameon=False,fontsize=13);note=chart['note'][lang];fig.text(.12,.07,'\n'.join(textwrap.wrap(note,95 if lang=='en'else 65)),fontsize=12,color='#475569')
    for ext in ['svg','png']:
     p=G/(chart['id']+'-'+lang+'.'+ext);assert not p.exists();fig.savefig(p,dpi=140 if ext=='png'else 100,metadata={'Date':None}if ext=='svg'else None);files.append(dict(file=p.relative_to(S).as_posix(),sha256=hashlib.sha256(p.read_bytes()).hexdigest(),chart=chart['id'],language=lang,format=ext))
    plt.close(fig)
manifest=dict(chapter='ML-22',scope='Complete coordinates and original plots derived from supplied exact Python comparison outputs, not a new fitting experiment.',charts=12,coordinateRows=len(coordinate_rows),coordinateFields=9*len(coordinate_rows),missingCoordinates=sum(r['defined']=='false'for r in coordinate_rows),SVG=0 if args.coordinates_only else 24,PNG=0 if args.coordinates_only else 24,sourceOriginalOrder='not calendar time',coordinateSHA256=hashlib.sha256((S/'source-chart-coordinates.csv').read_bytes()).hexdigest())
(S/'chart-generation-summary.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n',encoding='utf8');print(json.dumps(manifest,ensure_ascii=False))
