"""ECON24: reconstruct every actual analysis row from the three original-variable CSVs.
Python3.10+ standard library; optional matplotlib adds original vector figures.
Run: python compute-policy-cases.py --out ./fresh-python
The recorded decimal tokens are exact Fraction inputs. No precomputed answer file is read.
"""
from fractions import Fraction as Q
from pathlib import Path
import argparse,csv,json,math

def q(x):
 if x is None or isinstance(x,bool):raise ValueError('numeric value required; null does not mean zero')
 return Q(str(x))
def missing(x):return x is None or x.strip() in ('','.','null')
def nullable(x):return None if missing(x) else q(x)
def mean(x):return sum(x,Q())/len(x) if x else None
def serial(x):
 if isinstance(x,Q):return str(x)
 if isinstance(x,dict):return {k:serial(v)for k,v in x.items()}
 if isinstance(x,(list,tuple)):return list(map(serial,x))
 return x
def bounds(rows,L,H,monotone=False):
 L,H=q(L),q(H)
 if L>H:raise ValueError('ordered outcome support')
 if type(monotone)is not bool:raise ValueError('monotone must be a boolean')
 details=[];ids=set()
 for i,r in enumerate(rows):
  id=str(r.get('id',i));D=r['D'];w=q(r.get('weight',1));y=None if r['y']is None else q(r['y'])
  if id in ids:raise ValueError('duplicate unit id')
  ids.add(id)
  if D not in (0,1)or w<0:raise ValueError('binary D and nonnegative weight required')
  if y is not None and not L<=y<=H:raise ValueError('observed outcome outside maintained support')
  lo,hi=(L-H,H-L)if y is None else((y-H,y-L)if D else(L-y,H-y))
  if monotone:lo=max(Q(),lo)
  details.append(dict(id=id,D=D,weight=w,y=y,effectLower=lo,effectUpper=hi))
 mass=sum((r['weight']for r in details),Q())
 if mass<=0:raise ValueError('positive total weight required')
 groups=[]
 for D in (0,1):
  rs=[r for r in details if r['D']==D];obs=[r for r in rs if r['y']is not None];V=sum((r['weight']for r in rs),Q());O=sum((r['weight']for r in obs),Q());S=sum((r['weight']*r['y']for r in obs),Q())
  groups.append(dict(D=D,sourceUnits=len(rs),observedUnits=len(obs),totalWeight=V,observedWeight=O,missingWeight=V-O,observedSum=S,observedMean=S/O if O else None,factualLower=(S+(V-O)*L)/V if V else None,factualUpper=(S+(V-O)*H)/V if V else None))
 lo=sum((r['weight']*r['effectLower']for r in details),Q())/mass;hi=sum((r['weight']*r['effectUpper']for r in details),Q())/mass
 return dict(sourceUnits=len(rows),totalWeight=mass,lower=lo,upper=hi,width=hi-lo,monotoneResponseAssumed=monotone,groups=groups,unitContributions=details)
def sensitivity(c,bl,bh):
 c,bl,bh=map(q,(c,bl,bh))
 if bl>bh:raise ValueError('ordered bias range')
 return dict(contrast=c,biasLower=bl,biasUpper=bh,lower=c-bh,upper=c-bl,width=bh-bl,zeroConsistent=c-bh<=0<=c-bl,zeroEffectRequiresBias=c)
def transport(rows,L,H):
 L,H=q(L),q(H)
 if L>H:raise ValueError('ordered effect support')
 out=[]
 for r in rows:
  s,t=q(r['sourceWeight']),q(r['targetWeight'])
  if min(s,t)<0:raise ValueError('nonnegative stratum weights')
  if s:
   l,h=q(r['effectLower']),q(r['effectUpper'])
   if not L<=l<=h<=H:raise ValueError('stratum effect outside maintained support')
  else:
   if r['effectLower']is not None or r['effectUpper']is not None:raise ValueError('unsupported effects require explicit null')
   l,h=L,H
  out.append(dict(id=r['id'],sourceWeight=s,targetWeight=t,lower=l,upper=h,rawTargetSourceRatio=t/s if s else None))
 V=sum((r['targetWeight']for r in out),Q())
 if not V:raise ValueError('positive target mass')
 return dict(lower=sum((r['targetWeight']*r['lower']for r in out),Q())/V,upper=sum((r['targetWeight']*r['upper']for r in out),Q())/V,unsupportedShare=sum((r['targetWeight']for r in out if not r['sourceWeight']),Q())/V,strata=out)
def cashflow(L,H,rate,fixed,rows):
 L,H,rate,fixed=map(q,(L,H,rate,fixed))
 if L>H or rate<=-1:raise ValueError('ordered effect region and rate above minus one required')
 details=[]
 for r in rows:
  t=r['period']
  if type(t)is not int or not 0<=t<=100:raise ValueError('integer period0..100 required')
  c,k=q(r['coefficient']),q(r['cost']);d=(1+rate)**(-t)
  details.append(dict(period=t,coefficient=c,cost=k,factor=d,PVcoefficient=c*d,PVcost=k*d,atLower=(c*L-k)*d,atUpper=(c*H-k)*d))
 A=sum((r['PVcoefficient']for r in details),Q());C=fixed+sum((r['PVcost']for r in details),Q());a,b=A*L-C,A*H-C
 return dict(A=A,C=C,lower=min(a,b),upper=max(a,b),breakEven=C/A if A else None,breakEvenStatus='unique-affine-root'if A else('no-root-constant-net-value'if C else'every-effect-break-even'),flows=details)
def regret(a,b,cap=1,p=None):
 a,b,cap=map(q,(a,b,cap))
 if a>b or not 0<=cap<=1:raise ValueError('ordered gain interval and feasible cap0..1 required')
 positive=max(b,Q());negative=max(-a,Q())
 opt=Q()if not positive else cap if not negative else cap*positive/(positive+negative)
 family=(Q(),cap)if positive==negative==0 else(opt,opt)
 chosen=opt if p is None else q(p)
 if not 0<=chosen<=cap:raise ValueError('chosen fraction outside feasible cap')
 w=max(positive*(cap-chosen),negative*chosen)
 return dict(optimalFraction=opt,optimalLower=family[0],optimalUpper=family[1],chosen=chosen,worstRegret=w,optimalWorstRegret=max(positive*(cap-opt),negative*opt),noActionRegret=cap*positive,fullCapRegret=cap*negative)
def load_sources(folder):
 def read(n):
  with (folder/n).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))
 rawc=read('actual90-KOR-growth-and-CPI-original-1980-2024.csv');rawp=read('actual3613-NLS-original52-fields.csv');raws=read('actual410-NJPA-original46-fields.csv')
 assert len(rawc)==90 and len(rawp)==3613 and len(raws)==410
 c={}
 for row in rawc:
  year=int(row['year']);r=c.setdefault(year,dict(id=f'KOR:{year}',year=year,period=int(year>=2002)))
  field={'NY.GDP.MKTP.KD.ZG':'growth','FP.CPI.TOTL.ZG':'inflation'}[row['indicatorID']];assert field not in r;r[field]=nullable(row['valueToken'])
 country=[c[y]for y in range(1980,2025)]
 person=[dict(id='nls:'+r['originalSourceRow'],originalID=r['id'],D=int(q(r['ed76'])>=13),y=nullable(r['wage76']),schooling=q(r['ed76']),age=q(r['age76']),originalWeight=q(r['weight']))for r in rawp]
 def fte(r,s):
  parts=[nullable(r[k+s])for k in ['EMPFT','NMGRS','EMPPT']]
  return None if any(x is None for x in parts)else parts[0]+parts[1]+parts[2]/2
 company=[dict(id='store:'+r['originalSourceRow'],originalSheet=r['SHEET'],group=int(r['STATE']),before=fte(r,''),after=fte(r,'2'),chain=r['CHAIN'],status2=r['STATUS2'])for r in raws]
 return dict(country=country,person=person,company=company)
def compute(models):
 country,person,company=[models[k]for k in ['country','person','company']]
 splits=[]
 for split in range(1981,2025):
  groups=[[r['growth']for r in country if(r['year']>=split)==bool(g)and r['growth']is not None]for g in (0,1)];m=list(map(mean,groups));s=sensitivity(m[1]-m[0],-2,2)
  splits.append(dict(splitYear=split,earlierN=len(groups[0]),laterN=len(groups[1]),earlierMean=m[0],laterMean=m[1],**s))
 default=bounds(person,0,2500);mtr=bounds(person,0,2500,True);support=[]
 for H in (2500,3000,5000):
  for flag in (False,True):
   result=bounds(person,0,H,flag);support.append(dict(outcomeUpper=H,monotoneResponse=flag,sourceUnits=len(person),observedUnits=sum(r['y']is not None for r in person),missingUnits=sum(r['y']is None for r in person),lower=result['lower'],upper=result['upper'],width=result['width']))
 pUnits=[dict(**r,missing=r['y']is None,lower=u['effectLower'],upper=u['effectUpper'],mtrLower=v['effectLower'],mtrUpper=v['effectUpper'])for r,u,v in zip(person,default['unitContributions'],mtr['unitContributions'])]
 groups=[]
 for g in (0,1):
  allrows=[r for r in company if r['group']==g];paired=[r for r in allrows if r['before']is not None and r['after']is not None];b=mean([r['before']for r in paired]);a=mean([r['after']for r in paired]);groups.append(dict(group=g,sourceUnits=len(allrows),pairedUnits=len(paired),missingPairs=len(allrows)-len(paired),before=b,after=a,change=a-b))
 did=groups[1]['change']-groups[0]['change'];bias=[dict(radius=r,**sensitivity(did,-r,r))for r in (0,1,2,3,4)]
 units=[dict(**r,complete=r['before']is not None and r['after']is not None,change=r['after']-r['before']if r['before']is not None and r['after']is not None else None)for r in company]
 hist=[]
 for D in (0,1):
  for low in range(0,2500,100):hist.append(dict(D=D,binLower=low,binUpper=low+100,upperInclusive=low==2400,count=sum(r['y']is not None and r['D']==D and low<=r['y']and(r['y']<=low+100 if low==2400 else r['y']<low+100)for r in person)))
 cb=sensitivity(did,-3,3);valuation=cashflow(cb['lower'],cb['upper'],0,1,[dict(period=0,coefficient=2,cost=0)]);decision=regret(valuation['lower'],valuation['upper'],1)
 return dict(models=models,countrySplits=splits,person=default,personMTR=mtr,personSupportGrid=support,personUnitRows=pUnits,personHistogram=hist,companyGroups=groups,companyUnitRows=units,companyBiasGrid=bias,companyContrast=did,assumedValuation=valuation,assumedDecision=decision)
def write_all(result,out):
 out.mkdir(parents=True,exist_ok=True)
 tables={
 'computed-country-annual.csv':result['models']['country'],
 'computed-country-all-splits.csv':result['countrySplits'],
 'computed-person-unit-bounds.csv':result['personUnitRows'],
 'computed-person-group-summary.csv':result['person']['groups'],
 'computed-person-support-grid.csv':result['personSupportGrid'],
 'computed-person-wage-histogram.csv':result['personHistogram'],
 'computed-company-unit-pairs.csv':result['companyUnitRows'],
 'computed-company-group-summary.csv':result['companyGroups'],
 'computed-company-bias-grid.csv':result['companyBiasGrid'],
 'computed-policy-bridge.csv':[dict(stage=stage,metric=k,value=v)for stage in ['assumedValuation','assumedDecision']for k,v in result[stage].items()if not isinstance(v,(list,dict))]
 }
 for name,rows in tables.items():
  with (out/name).open('w',encoding='utf-8',newline='')as f:
   w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(serial(rows))
 (out/'computed-all-cases.json').write_text(json.dumps(serial(result),ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
 (out/'scope.txt').write_text('Actual retained-source finite-frame computations. Country split is arbitrary teaching history,not DID. NLS equal weights/support are maintained;596missing factual wages remain unknown. NJPA uses384FTE-only complete pairs of410,no closure zero imputation. Valuation2/fixedcost1 and decision are illustrative assumptions,not observed monetary benefits. No confidence interval or causal identification is certified.\n',encoding='utf-8')
 return tables
def plots(result,out):
 try:
  import matplotlib
  matplotlib.use('Agg')
  import matplotlib.pyplot as plt
 except ImportError:return []
 out=out/'figures';out.mkdir(exist_ok=True);files=[]
 fig,ax=plt.subplots(figsize=(9,4.8),layout='constrained');rows=result['models']['country'];ax.plot([r['year']for r in rows],[float(r['growth'])for r in rows],marker='o',markersize=3);ax.axhline(0,color='#666',linewidth=.7);ax.axvline(2001.5,color='#b36f37',linestyle='--',label='Assumed teaching split: 2002');ax.set(xlabel='Year',ylabel='Annual real-GDP growth (%)',title='Korea 1980–2024: 45 actual country-years, not a policy design');ax.legend(fontsize=9);p=out/'country-growth.svg';fig.savefig(p);plt.close(fig);files.append(str(p))
 fig,ax=plt.subplots(figsize=(9,4.8),layout='constrained')
 for D,color in [(0,'#285c70'),(1,'#b36f37')]:
  rs=[r for r in result['personHistogram']if r['D']==D];ax.stairs([r['count']for r in rs],list(range(0,2501,100)),color=color,label=f'Constructed schooling group D={D}')
 ax.set(xlabel='Observed nominal 1976 hourly wage, cents (100-cent bins)',ylabel='Observed individuals',title='3017 observed wages; 596 missing remain outside histogram');ax.legend(fontsize=9);p=out/'person-observed-wages.svg';fig.savefig(p);plt.close(fig);files.append(str(p))
 fig,ax=plt.subplots(figsize=(8,4.8),layout='constrained')
 for r,label in zip(result['companyGroups'],['PA: 75 complete pairs','NJ: 309 complete pairs']):ax.plot([0,1],[float(r['before']),float(r['after'])],marker='o',label=label)
 ax.set_xticks([0,1],['Wave 1','Wave 2']);ax.set(ylabel='Mean FTE, identical paired frame',title='384 FTE-only pairs from 410 stores; observed DID 2.75');ax.legend(fontsize=9);p=out/'company-paired-means.svg';fig.savefig(p);plt.close(fig);files.append(str(p));return files
def main():
 parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--sources',type=Path,default=Path(__file__).resolve().parent);parser.add_argument('--out',type=Path,required=True);parser.add_argument('--plots',action='store_true');args=parser.parse_args()
 result=compute(load_sources(args.sources));tables=write_all(result,args.out);figures=plots(result,args.out)if args.plots else []
 print(json.dumps(dict(program='ECON24-full-actual-cases',countryRows=len(result['models']['country']),personRows=len(result['models']['person']),observedWages=sum(r['y']is not None for r in result['models']['person']),companyRows=len(result['models']['company']),pairedStores=sum(r['complete']for r in result['companyUnitRows']),DID=str(result['companyContrast']),ATE=[str(result['person'][k])for k in ['lower','upper']],CSVtables=len(tables),figures=len(figures))))
if __name__=='__main__':main()
