# ML23 factual native CSV + explicitly frozen prior-model parameters.
# No engine, source candidate, predictions or metric answers are inputs.
# Python uses exact rational arithmetic. This author program is NOT an
# additional independent peer oracle. Constructed event/arrival indices
# are teaching overlays, not observed dates or operational logs.
# UCI Wine Quality DOI10.24432/C56S3T; Card NLS; Iranian Churn DOI10.24432/C5JW3Z.
from pathlib import Path
from fractions import Fraction as F
from collections import Counter
import csv,json,hashlib,math,sys
sys.set_int_max_str_digits(0)

CONFIG={'country': {'features': ['fixed acidity', 'volatile acidity', 'citric acid', 'residual sugar', 'chlorides', 'free sulfur dioxide', 'total sulfur dioxide', 'density', 'pH', 'sulphates', 'alcohol', 'declaredRedWineIndicator'], 'task': 'regression', 'yUnit': 'native ordered sensory quality score0..10', 'driftIndex': 10, 'cuts': ['9', '10', '11', '12'], 'riskCap': '1', 'labelKO': '와인 원기록', 'labelEN': 'Wine records', 'unitKO': '원 품질 점수'}, 'person': {'features': ['ed76', 'age76'], 'task': 'regression', 'yUnit': 'native trimmed1976log hourly wage', 'driftIndex': 0, 'cuts': ['8', '12', '16'], 'riskCap': '1/4', 'labelKO': 'NLS 개인 원기록', 'labelEN': 'NLS individual records', 'unitKO': '원 1976년 로그 시급'}, 'company': {'features': ['Call  Failure', 'Subscription  Length', 'Seconds of Use', 'Age'], 'task': 'binary', 'yUnit': 'native Churn0/1', 'driftIndex': 0, 'cuts': ['0', '3', '10'], 'riskCap': '1/5', 'labelKO': '통신 고객 원기록', 'labelEN': 'Telecom customer records', 'unitKO': '0·1 이탈 라벨'}}
MODEL_SHA256='94fef62c68956f6182ef0c1b6c26b5b0324f7140c3dcb61960d045ac59dcdd2a'

def Q(x):return None if x is None or x in ('','.') else F(str(x))

def canonical(v):return None if Q(v) is None else str(Q(v))

def fingerprint(tag,values):return tag+':'+hashlib.sha256(json.dumps([canonical(x)for x in values],separators=(',',':')).encode()).hexdigest()

def split(rows,seed=20261104,pattern=('test','validation','train','train')):
 order=sorted(set(r['group'] for r in rows));state=seed
 for j in range(len(order)-1,0,-1):state=(1664525*state+1013904223)&0xffffffff;k=state%(j+1);order[k],order[j]=order[j],order[k]
 roles={g:(i,pattern[i%len(pattern)]) for i,g in enumerate(order)}
 return roles,state,order

NATIVE_SHA256={'actual1599-red-wine-original12-fields.csv': '77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00', 'actual4898-white-wine-original12-fields.csv': '50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef', 'actual3613-NLS-original52-fields.csv': '6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1', 'actual3150-churn-original14-fields.csv': '1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764'}

def read_sources(directory,seed):
 def read(name):
  p=directory/name
  if hashlib.sha256(p.read_bytes()).hexdigest()!=NATIVE_SHA256[name]:raise ValueError('Native file hash differs: '+name)
  with p.open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))
 sources={};wine=[]
 for typ,n in [('red',1599),('white',4898)]:
  table=read(f'actual{n}-{typ}-wine-original12-fields.csv');assert len(table)==n;features=[k for k in table[0]if k not in ['sourceRow','wineType','quality']];assert len(features)==11
  for r in table:
   i=int(r['sourceRow']);red='1'if typ=='red'else'0';nativeX=[r[k]for k in features];wine.append(dict(id=f'wine-{typ}-row:{i}',sourceRow=f'{typ}:{i}',originalID=None,group=fingerprint('wine-predictors',[red]+nativeX),cohort=typ,x=list(map(Q,nativeX+[red])),y=Q(r['quality'])))
 sources['country']=wine
 table=read('actual3613-NLS-original52-fields.csv');assert len(table)==3613;sources['person']=[dict(id='nls-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],group='nls-id:'+r['id'],cohort='schooling-over12'if Q(r['ed76'])>12 else'schooling-at-most12',x=[Q(r['ed76']),Q(r['age76'])],y=Q(r['lwage76']))for r in table]
 table=read('actual3150-churn-original14-fields.csv');assert len(table)==3150;predictors=[k for k in table[0]if k not in ['sourceRow','Churn']];assert len(predictors)==13;sources['company']=[dict(id='customer-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=None,group=fingerprint('customer-predictors',[r[k]for k in predictors]),cohort='pay-as-you-go'if r['Tariff Plan']=='1'else'contractual'if r['Tariff Plan']=='2'else'other-native-tariff',x=[Q(r[k])for k in ['Call  Failure','Subscription  Length','Seconds of Use','Age']],y=Q(r['Churn']))for r in table]
 for kind,rows in sources.items():
  assignments,state,order=split(rows,seed)
  for r in rows:
   rank,planned=assignments[r['group']];r.update(w=F(1),splitRank=rank,plannedRole=planned,eligible=r['y']is not None and None not in r['x']);r['role']=planned if r['eligible']else'excluded'
 return sources

def q(x):return None if x is None else F(str(x))

def defined(x,reason):return dict(defined=True,value=x)if x is not None else dict(defined=False,reason=reason)

def hist(a):
 cuts=list(map(q,a['cuts']))
 def frame(rows):
  Wt=sum((q(r.get('weight','1'))for r in rows),F(0));use=[(q(r['value']),q(r.get('weight','1')))for r in rows if q(r.get('weight','1'))>0];missing=sum((w for v,w in use if v is None),F(0));numeric=Wt-missing;bins=[]
  for i in range(len(cuts)+1):
   mass=sum((w for v,w in use if v is not None and (i==0 or v>=cuts[i-1])and(i==len(cuts)or v<cuts[i])),F(0));bins.append(dict(index=i,lower=cuts[i-1]if i else None,upper=cuts[i]if i<len(cuts)else None,lowerInclusive=i>0,upperInclusive=False,mass=mass,probability=defined(mass/numeric if numeric else None,'no-positive-numeric-mass')))
  return dict(rows=len(rows),positiveRows=len(use),totalMass=Wt,numericMass=numeric,missingMass=missing,missingRows=sum(v is None for v,w in use),numericMean=defined(sum((v*w for v,w in use if v is not None),F(0))/numeric if numeric else None,'no-positive-numeric-mass'),missingFraction=defined(missing/Wt if Wt else None,'zero-total-mass'),bins=bins)
 A=frame(a['reference']);B=frame(a['current']);tv=sum((abs(x['probability']['value']-y['probability']['value'])for x,y in zip(A['bins'],B['bins'])),F(0))/2 if A['numericMass']and B['numericMass']else None
 out=dict(reference=A,current=B,cuts=cuts,totalVariation=defined(tv,'both-frames-need-positive-numeric-mass'),overlap=defined(1-tv if tv is not None else None,'both-frames-need-positive-numeric-mass'))
 if'lossBounds'in a:out['boundedFunctionDifference']=defined((q(a['lossBounds'][1])-q(a['lossBounds'][0]))*tv if tv is not None else None,'both-frames-need-positive-numeric-mass')
 else:out['boundedFunctionDifference']=defined(None,'loss-bounds-not-declared')
 return out

def stream(a):
 cutoff=a.get('cutoff',0);start=a.get('start',0);task=a.get('task','regression');threshold=q(a.get('threshold','1/2'));out=[]
 for i,b in enumerate(a['rows']):
  event=b['event'];at=b['labelAt'];y=q(b['y']);p=q(b['prediction']);w=q(b.get('weight','1'));seen=start<=event<=cutoff;arrived=seen and at is not None and at<=cutoff and y is not None
  label='outside-event-window'if not seen else'native-label-missing'if y is None else'arrival-unspecified'if at is None else'waiting-label'if at>cutoff else'arrived';state='outside-event-window'if not seen else'zero-weight'if not w else'missing-prediction'if p is None else'ready'if label=='arrived'else label
  out.append(dict(id=b.get('id','row:'+str(i)),index=i,event=event,labelAt=at,cohort=b.get('cohort','all'),group=b.get('group',b.get('id','row:'+str(i))),weight=w,nativeY=y,prediction=p,seen=seen,arrived=arrived,labelState=label,state=state,eligible=state=='ready'))
 return out,cutoff,start,task,threshold

def available(rows):
 total=sum((r['weight']for r in rows if r['seen']and r['weight']>0),F(0));arrived=sum((r['weight']for r in rows if r['seen']and r['arrived']and r['weight']>0),F(0));scored=sum((r['weight']for r in rows if r['eligible']),F(0))
 return dict(inputRows=len(rows),eventWindowRows=sum(r['seen']for r in rows),arrivedLabelRows=sum(r['arrived']for r in rows),scoredRows=sum(r['eligible']for r in rows),stateCounts=dict(Counter(r['state']for r in rows)),labelStateCounts=dict(Counter(r['labelState']for r in rows)),seenMass=total,arrivedMass=arrived,scoredMass=scored,arrivalFraction=defined(arrived/total if total else None,'no-positive-event-window-mass'))

def risks(rows,task,threshold):
 use=[r for r in rows if r['eligible']];total=sum((r['weight']for r in use),F(0));out=dict(rows=len(use),mass=total)
 if not total:
  out.update({key:defined(None,'no-positive-ready-mass')for key in ['MSE','MAE','R2']+(['Brier','accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC']if task=='binary'else[])});return out
 mean=sum((r['weight']*r['nativeY']for r in use),F(0))/total;SSE=sum((r['weight']*(r['prediction']-r['nativeY'])**2 for r in use),F(0));SST=sum((r['weight']*(r['nativeY']-mean)**2 for r in use),F(0));mae=sum((r['weight']*abs(r['prediction']-r['nativeY'])for r in use),F(0))/total
 out.update(meanY=mean,SSE=SSE,SST=SST,MSE=defined(SSE/total,''),MAE=defined(mae,''),R2=defined(1-SSE/SST if SST else None,'constant-ready-outcome'))
 if task=='binary':
  mass={k:F(0)for k in ['TP','FP','TN','FN']};num={k:0 for k in mass}
  for r in use:
   pred=r['prediction']>=threshold;truth=bool(r['nativeY']);key=('T'if pred==truth else'F')+('P'if pred else'N');mass[key]+=r['weight'];num[key]+=1
  P=mass['TP']+mass['FN'];N=mass['TN']+mass['FP'];tpr=mass['TP']/P if P else None;tnr=mass['TN']/N if N else None
  # Own pair enumeration deliberately differs from the JS sorted tie blocks.
  positives=[r for r in use if r['nativeY']==1];negatives=[r for r in use if r['nativeY']==0];wins=sum((a['weight']*b['weight']*(F(1)if a['prediction']>b['prediction']else F(1,2)if a['prediction']==b['prediction']else F(0))for a in positives for b in negatives),F(0));auc=wins/(P*N)if P and N else None
  out.update(Brier=out['MSE'],threshold=threshold,confusionMass=mass,confusionRows=num,positiveMass=P,negativeMass=N,accuracy=defined((mass['TP']+mass['TN'])/total,''),positiveRecall=defined(tpr,'no-ready-positive-class'),negativeRecall=defined(tnr,'no-ready-negative-class'),precision=defined(mass['TP']/(mass['TP']+mass['FP'])if mass['TP']+mass['FP']else None,'no-positive-prediction-mass'),balancedAccuracy=defined((tpr+tnr)/2 if tpr is not None and tnr is not None else None,'both-ready-classes-required'),AUROC=defined(auc,'both-ready-classes-required'))
 return out

def monitor(a,loss=True):
 rows,cutoff,start,task,threshold=stream(a);masked=[]
 for r in rows:
  b={k:r[k]for k in ['id','index','event','labelAt','cohort','group','weight','labelState','state','eligible']};b.update(eventSeen=r['seen'],visibleY=r['nativeY']if r['arrived']else None,visiblePrediction=r['prediction']if r['seen']else None)
  if loss:
   b['squaredLoss']=defined((r['prediction']-r['nativeY'])**2 if r['eligible']else None,'not-ready-for-scoring')
   if task=='binary':b['correct']=defined((r['prediction']>=threshold)==bool(r['nativeY'])if r['eligible']else None,'not-ready-for-classification')
  masked.append(b)
 out=dict(cutoff=cutoff,start=start,availability=available(rows),rows=masked)
 if loss:out.update(task=task,threshold=threshold if task=='binary'else None,overall=risks(rows,task,threshold),byCohort=[dict(cohort=cohort,**risks([r for r in rows if r['cohort']==cohort],task,threshold))for cohort in dict.fromkeys(r['cohort']for r in rows)])
 return out

def gate(a):
 risk=q(a['validationRisk']);cap=q(a['maximumRisk']);tv=q(a['driftTV']);maxTV=q(a['maximumDrift']);arrival=q(a['arrivedFraction']);minimum=q(a['minimumArrived']);violations=a['contractViolations']
 tests=[dict(name='input-contract',defined=True,passed=violations==0,value=violations,comparison='equal zero'),dict(name='frozen-validation-risk',defined=risk is not None,passed=risk<=cap if risk is not None else None,value=risk,threshold=cap,comparison='at most',unit=a['riskUnit']),dict(name='declared-binned-TV',defined=tv is not None,passed=tv<=maxTV if tv is not None else None,value=tv,threshold=maxTV,comparison='at most'),dict(name='arrived-label-fraction',defined=arrival is not None,passed=arrival>=minimum if arrival is not None else None,value=arrival,threshold=minimum,comparison='at least')];failed=any(t['defined']and not t['passed']for t in tests);unknown=any(not t['defined']for t in tests)
 return dict(decision='hold'if failed else'insufficient-information'if unknown else'allow-simulated-release',checks=tests,allKnown=not unknown,anyFailed=failed)

def model_parameters(file):
 if hashlib.sha256(file.read_bytes()).hexdigest()!=MODEL_SHA256:raise ValueError('Frozen parameter artifact hash differs')
 models={}
 with file.open(encoding='utf-8',newline='')as f:
  for r in csv.DictReader(f):
   entries=models.setdefault(r['dataset'],{}).setdefault(r['parameter'],{})
   i=int(r['index'])
   if i in entries:raise ValueError('Duplicate parameter coordinate')
   entries[i]=F(r['valueExact'])
 for kind,m in models.items():
  p=len(CONFIG[kind]['features'])
  for key,n in [('theta',p+1),('meanX',p),('scales',p),('baselineMean',1)]:
   if sorted(m[key])!=list(range(n)):raise ValueError('Parameter coordinates differ')
   m[key]=[m[key][i]for i in range(n)]
 return models
def value(x):return ''if x is None else str(x).lower()if isinstance(x,bool)else str(x)
def approximate(x):
 if x is None:return None
 try:v=float(x)
 except OverflowError:return None
 return v if math.isfinite(v)else None
def write_csv(folder,name,rows,columns):
 with(folder/name).open('w',encoding='utf-8',newline='')as f:
  w=csv.DictWriter(f,fieldnames=columns,lineterminator='\n');w.writeheader();w.writerows({k:value(r.get(k))for k in columns}for r in rows)
def run(source_dir,model_file,output_dir):
 if output_dir.exists():raise ValueError('Preserve outputs: use a new output directory')
 output_dir.mkdir(parents=True);native=read_sources(source_dir,20261104);models=model_parameters(model_file)
 prediction_rows=[];arrival_rows=[];availability_rows=[];risk_rows=[];hist_rows=[];gate_rows=[];visible_rows=[];coordinates=[];figures={};checks=0
 for kind,records in native.items():
  cfg=CONFIG[kind];model=models[kind];theta,mu,scale=[model[k]for k in ['theta','meanX','scales']];binary=cfg['task']=='binary';predictions={};baseline=model['baselineMean'][0]
  for r in records:
   raw=theta[0]+sum((b*(x-m)/s for b,x,m,s in zip(theta[1:],r['x'],mu,scale)),F(0))if None not in r['x']else None
   pred=min(F(1),max(F(0),raw))if binary and raw is not None else raw;predictions[r['id']]=pred
   prediction_rows.append(dict(dataset=kind,id=r['id'],sourceRow=r['sourceRow'],originalID=r['originalID'],group=r['group'],cohort=r['cohort'],plannedRole=r['plannedRole'],role=r['role'],eligible=r['eligible'],y=r['y'],rawPrediction=raw,prediction=pred,baselinePrediction=baseline));checks+=1
  validation=[r for r in records if r['role']=='validation'];mass=sum((r['w']for r in validation),F(0));validationMSE=sum((r['w']*(predictions[r['id']]-r['y'])**2 for r in validation),F(0))/mass
  test=[r for r in records if r['plannedRole']=='test'];N=len(test);cutoffs=sorted({0,1,5,10,20,50,100,200,N,N+8});snapshots={};schedules={};drifts={};ref=[dict(value=str(r['x'][cfg['driftIndex']]),weight='1')for r in records if r['role']=='train']
  for cutoff in cutoffs:
   current=[dict(value=str(r['x'][cfg['driftIndex']]),weight='1')for r in test[:cutoff]];d=hist(dict(reference=ref,current=current,cuts=cfg['cuts']));drifts[cutoff]=d
   for i,(a,b)in enumerate(zip(d['reference']['bins'],d['current']['bins'])):
    hist_rows.append(dict(dataset=kind,cutoff=cutoff,bin=i,lower=a['lower'],upper=a['upper'],referenceMass=a['mass'],currentMass=b['mass'],referenceProbability=a['probability'].get('value'),currentProbability=b['probability'].get('value'),TV=d['totalVariation'].get('value'),referenceMissingFraction=d['reference']['missingFraction'].get('value'),currentMissingFraction=d['current']['missingFraction'].get('value')))
  for rule in ['cyclic','outcome-dependent']:
   rows=[]
   for i,r in enumerate(test,1):
    lag=None if r['y']is None else(i-1)%5 if rule=='cyclic'else 8 if r['y']>=(1 if binary else 6)else 1
    at=None if lag is None else i+lag;row=dict(id=r['id'],event=i,labelAt=at,y=str(r['y'])if r['y']is not None else None,prediction=str(predictions[r['id']])if predictions[r['id']]is not None else None,weight='1',cohort=r['cohort'],group=r['group']);rows.append(row)
    arrival_rows.append(dict(dataset=kind,rule=rule,event=i,id=r['id'],originalID=r['originalID'],cohort=r['cohort'],group=r['group'],historicalY=r['y'],prediction=predictions[r['id']],labelAt=at,constructedDelay=lag,nativeMissing=r['y']is None))
   schedules[rule]=rows;snapshots[rule]={}
   for cutoff in cutoffs:
    snap=monitor(dict(rows=rows,cutoff=cutoff,task=cfg['task']));snapshots[rule][cutoff]=snap;a=snap['availability'];counts=a['stateCounts']
    availability_rows.append(dict(dataset=kind,rule=rule,cutoff=cutoff,inputRows=a['inputRows'],eventWindowRows=a['eventWindowRows'],arrivedLabelRows=a['arrivedLabelRows'],scoredRows=a['scoredRows'],seenMass=a['seenMass'],arrivedMass=a['arrivedMass'],scoredMass=a['scoredMass'],arrivalFraction=a['arrivalFraction'].get('value'),defined=a['arrivalFraction']['defined'],outsideWindow=counts.get('outside-event-window',0),nativeMissing=counts.get('native-label-missing',0),waiting=counts.get('waiting-label',0),unspecified=counts.get('arrival-unspecified',0),missingPrediction=counts.get('missing-prediction',0),zeroWeight=counts.get('zero-weight',0)))
    for cohort,z in [('all',snap['overall'])]+[(g['cohort'],g)for g in snap['byCohort']]:
     for name in ['MSE','MAE','R2']+(['Brier','accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC']if binary else[]):
      metric=z[name];qv=metric.get('value');unit=cfg['yUnit']+' squared'if name in ['MSE','Brier']else cfg['yUnit']if name=='MAE'else'dimensionless'
      risk_rows.append(dict(dataset=kind,rule=rule,cutoff=cutoff,cohort=cohort,metric=name,defined=metric['defined'],exact=qv,approx=approximate(qv),unit=unit,rows=z['rows'],mass=z['mass']))
    d=drifts[cutoff];g=gate(dict(validationRisk=str(validationMSE),maximumRisk=cfg['riskCap'],driftTV=str(d['totalVariation']['value'])if d['totalVariation']['defined']else None,maximumDrift='1/5',arrivedFraction=str(a['arrivalFraction']['value'])if a['arrivalFraction']['defined']else None,minimumArrived='4/5',contractViolations=0,riskUnit=cfg['yUnit']+' squared'))
    for c in g['checks']:gate_rows.append(dict(dataset=kind,rule=rule,cutoff=cutoff,decision=g['decision'],check=c['name'],defined=c['defined'],passed=c['passed'],value=c['value'],threshold=c.get('threshold'),comparison=c['comparison'],unit=c.get('unit','count'if c['name']=='input-contract'else'dimensionless')))
    if cutoff==200:
     for r in snap['rows']:visible_rows.append(dict(dataset=kind,rule=rule,cutoff=cutoff,**{k:r[k]for k in ['id','index','event','labelAt','cohort','group','weight','eventSeen','labelState','state','eligible','visibleY','visiblePrediction']},squaredLoss=r['squaredLoss'].get('value'),correct=r.get('correct',{}).get('value')))
  charts=[]
  def point(id,x,y):return dict(id=id,x=approximate(x),y=approximate(y),xExact=value(x),yExact=None if y is None else value(y))
  def chart(key,title,xlabel,ylabel,note,series,**kw):charts.append(dict(id=kind+'-'+key,type='scatter',title=title,xLabel=xlabel,yLabel=ylabel,note=note,series=series,**kw))
  full=snapshots['cyclic'][N+8];fullrisk=full['overall']['MSE'].get('value');maxCoverage=full['availability']['arrivalFraction'].get('value');defaultNote=dict(ko='실제 원값·동결 모형에 별도로 구성한 추상 인덱스 일정. 실제 날짜·지연 기록이 아님.',en='Factual values and a frozen model under separately constructed index schedules; not observed dates or delay logs.')
  chart('arrived-risk',dict(ko=cfg['labelKO']+' · 도착 라벨 MSE',en=cfg['labelEN']+': arrived-label MSE'),dict(ko='구성한 기준 인덱스 · 달력 아님',en='Constructed cutoff index, not calendar time'),dict(ko=cfg['unitKO']+'의 제곱',en=cfg['yUnit']+' squared'),defaultNote,[dict(label=dict(ko='순환 지연의 도착 MSE',en='Cyclic-delay arrived MSE'),data=[point(str(c),F(c),snapshots['cyclic'][c]['overall']['MSE'].get('value'))for c in cutoffs]),dict(label=dict(ko='결과 의존 지연의 도착 MSE',en='Outcome-dependent arrived MSE'),data=[point(str(c),F(c),snapshots['outcome-dependent'][c]['overall']['MSE'].get('value'))for c in cutoffs]),dict(label=dict(ko='원 비결측 라벨 전체 공개 기준',en='All native nonmissing labels released'),data=[point(str(c),F(c),fullrisk)for c in cutoffs])])
  chart('arrival-coverage',dict(ko=cfg['labelKO']+' · 라벨 도착 비율',en=cfg['labelEN']+': label-arrival coverage'),dict(ko='구성한 기준 인덱스 · 달력 아님',en='Constructed cutoff index, not calendar time'),dict(ko='현재 이벤트 비중 중 비율',en='Fraction of current event weight'),defaultNote,[dict(label=dict(ko='순환 지연',en='Cyclic delay'),data=[point(str(c),F(c),snapshots['cyclic'][c]['availability']['arrivalFraction'].get('value'))for c in cutoffs]),dict(label=dict(ko='결과 의존 지연',en='Outcome-dependent delay'),data=[point(str(c),F(c),snapshots['outcome-dependent'][c]['availability']['arrivalFraction'].get('value'))for c in cutoffs]),dict(label=dict(ko='최종 예정 대상의 원 라벨 비율',en='Native-label fraction in final target frame'),data=[point(str(c),F(c),maxCoverage)for c in cutoffs])],yBounds=[0,1])
  h=drifts[200];chart('feature-bins',dict(ko=cfg['labelKO']+' · 기준 200의 특징 분포',en=cfg['labelEN']+': feature bins at cutoff 200'),dict(ko='공통 구간 위치 · 수치표에서 경계 확인',en='Common bin position; boundaries in table'),dict(ko='양의 수치 비중 안의 비율',en='Fraction within positive numeric mass'),dict(ko='특징 '+cfg['features'][cfg['driftIndex']]+'의 제한된 구간 진단. 결과 위험 보장이 아님.',en='Limited binned diagnostic for '+cfg['features'][cfg['driftIndex']]+', not a risk guarantee.'),[dict(label=dict(ko='고정 훈련 기준',en='Frozen training reference'),data=[point(str(b['index']),F(b['index']+1),b['probability'].get('value'))for b in h['reference']['bins']]),dict(label=dict(ko='기준 200까지 이벤트',en='Events through cutoff 200'),data=[point(str(b['index']),F(b['index']+1),b['probability'].get('value'))for b in h['current']['bins']])],xTicks=list(range(1,len(h['reference']['bins'])+1)),yBounds=[0,1])
  chart('constructed-delay',dict(ko=cfg['labelKO']+' · 구성한 지연 인덱스',en=cfg['labelEN']+': constructed delay indices'),dict(ko='예정 시험 원행의 이벤트 인덱스',en='Event index of planned test records'),dict(ko='도착 − 이벤트 · 추상 인덱스',en='Arrival minus event, abstract indices'),defaultNote,[dict(label=dict(ko='순환 규칙',en='Cyclic rule'),data=[point(r['id'],F(r['event']),None if r['labelAt']is None else F(r['labelAt']-r['event']))for r in schedules['cyclic']]),dict(label=dict(ko='결과 의존 규칙',en='Outcome-dependent rule'),data=[point(r['id'],F(r['event']),None if r['labelAt']is None else F(r['labelAt']-r['event']))for r in schedules['outcome-dependent']])])
  figures[kind]=dict(charts=charts,scope=defaultNote)
 for kind,g in figures.items():
  for chart in g['charts']:
   for s,series in enumerate(chart['series']):
    for i,p in enumerate(series['data']):coordinates.append(dict(dataset=kind,chart=chart['id'],series=s,index=i,id=p['id'],xExact=p['xExact'],yExact=p['yExact'],defined=p['yExact']is not None))
 for name,rows in [('computed-frozen-predictions.csv',prediction_rows),('computed-event-arrivals.csv',arrival_rows),('computed-window-availability.csv',availability_rows),('computed-window-risks.csv',risk_rows),('computed-feature-histograms.csv',hist_rows),('computed-release-gates.csv',gate_rows),('computed-cutoff200-visible-ledger.csv',visible_rows),('computed-chart-coordinates.csv',coordinates)]:write_csv(output_dir,name,rows,list(rows[0]))
 (output_dir/'source-figure-data.json').write_text(json.dumps(figures,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
 (output_dir/'calculation-summary.json').write_text(json.dumps(dict(nativeRecords=len(prediction_rows),constructedScheduleRows=len(arrival_rows),availabilitySnapshots=len(availability_rows),riskMetricRows=len(risk_rows),histogramRows=len(hist_rows),gateConditionRows=len(gate_rows),visibleProjectionRows=len(visible_rows),chartSlots=len(coordinates),checks=checks,scope='Factual source rows and a previously frozen model; event/arrival schedules are constructed overlays. Python exact author reproduction, not an external oracle or prospective operation.'),ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
 print(json.dumps(dict(records=len(prediction_rows),snapshots=len(availability_rows),chartSlots=len(coordinates)),ensure_ascii=False))
if __name__=='__main__':
 import argparse
 parser=argparse.ArgumentParser(description='ML23 actual-native-CSV/frozen-model monitoring reproduction');parser.add_argument('--source-dir',type=Path,default=Path(__file__).parent);parser.add_argument('--model-file',type=Path,default=Path(__file__).parent/'frozen-model-parameters.csv');parser.add_argument('--output-dir',type=Path,required=True);args=parser.parse_args();run(args.source_dir,args.model_file,args.output_dir)
