#!/usr/bin/env python3
"""METR24 source-only exact descriptive reproduction.
The Fraction projection functions below are copied by value from the author's
separate mathematical reference. They are not an external independent oracle.
Reads only the three factual CSVs in --input-dir; creates a fresh --output-dir.
No engine/models/precomputed answer or another chapter's files are imported.
"""
from fractions import Fraction as F
def dot(x,y):return sum((a*b for a,b in zip(x,y)),F())
def basis(columns):
    out=[]
    for col in columns:
        v=col[:]
        for z in out:
            a=dot(v,z)/dot(z,z);v=[x-a*y for x,y in zip(v,z)]
        if dot(v,v):out.append(v)
    return out
def residual(v,B):
    for z in B:
        a=dot(v,z)/dot(z,z);v=[x-a*y for x,y in zip(v,z)]
    return v
def variances(rows):
    g={}
    for r in rows:
        key=(type(r['group']).__name__,str(r['group']));g[key]=g.get(key,F())+r['influence']
    return {'rowHC0Variance':sum((r['influence']**2 for r in rows),F()),'groupHC0Variance':sum((v*v for v in g.values()),F()),'reportingGroups':len(g)}
def ref_plan(rows,d):
    data=[];eligible=[]
    for i,r in enumerate(rows):
        v={k:None if z is None else F(str(z)) for k,z in r['values'].items()}
        win=(d.get('periodLower',-10**9)<=r.get('period',0)<=d.get('periodUpper',10**9))
        keys=[d['outcome']] if d['kind']=='mean' else [d['outcome'],d['exposure']]+d.get('controls',[]) if d['kind']=='ols' else [d['groupKey'],d['pre'],d['post']]
        good=win and all(v.get(k) is not None for k in keys)
        if d['kind']=='did' and d.get('frame','paired')=='available':good=win and v.get(d['groupKey']) is not None and (v.get(d['pre']) is not None or v.get(d['post']) is not None)
        item={'index':i,'id':r['id'],'group':r.get('group',r['id']),'v':v,'eligible':good}
        data.append(item)
        if good:eligible.append(item)
    n=len(eligible);result={'sourceRows':len(rows),'eligibleRows':n,'excludedRows':len(rows)-n,'eligibility':[r['eligible'] for r in data]}
    if d['kind']=='mean':
        total=sum((r['v'][d['outcome']] for r in eligible),F());mean=total/n if n else None
        rr=[{'index':r['index'],'id':r['id'],'group':r['group'],'fitted':mean,'residual':r['v'][d['outcome']]-mean,'linearWeight':F(1,n),'influence':(r['v'][d['outcome']]-mean)/n} for r in eligible]
        sse=sum((r['residual']**2 for r in rr),F()) if n else None
        result.update(estimate=mean,emptySum=total,SSE=sse,sampleVariance=sse/(n-1) if n>1 else None,degreesFreedom=max(0,n-1),rows=rr,variance=variances(rr) if n else None)
    elif d['kind']=='ols':
        y=[r['v'][d['outcome']] for r in eligible];x=[r['v'][d['exposure']] for r in eligible]
        B=basis([[F(1)]*n]+[[r['v'][k] for r in eligible] for k in d.get('controls',[])])
        xr=residual(x,B);yr=residual(y,B);sxx=dot(xr,xr);sxy=dot(xr,yr);beta=sxy/sxx if sxx else None
        rr=[]
        for i,r in enumerate(eligible):
            e=yr[i]-beta*xr[i] if beta is not None else yr[i]
            rr.append({'index':r['index'],'id':r['id'],'group':r['group'],'residualExposure':xr[i],'residualOutcome':yr[i],'fitted':y[i]-e,'residual':e,'linearWeight':xr[i]/sxx if sxx else None,'influence':xr[i]*e/sxx if sxx else None})
        sse=sum((r['residual']**2 for r in rr),F());rank=len(B)+bool(sxx);df=n-rank
        result.update(estimate=beta,Sxx=sxx,Sxy=sxy,SSE=sse,rank=rank,controlRank=len(B),degreesFreedom=df,residualMeanSquare=sse/df if df else None,rows=rr,variance=variances(rr) if sxx else None)
    else:
        cells=[]
        for g,w,key,sign in [(0,'pre',d['pre'],1),(0,'post',d['post'],-1),(1,'pre',d['pre'],-1),(1,'post',d['post'],1)]:
            vs=[r['v'][key] for r in eligible if r['v'][d['groupKey']]==g and r['v'].get(key) is not None];total=sum(vs,F());cells.append({'group':g,'wave':w,'key':key,'sign':sign,'n':len(vs),'total':total,'mean':total/len(vs) if vs else None})
        ok=all(c['n'] for c in cells);est=sum((c['sign']*c['mean'] for c in cells),F()) if ok else None;rr=[]
        for r in eligible:
            components=[]
            for c in cells:
                if r['v'][d['groupKey']]==c['group'] and r['v'].get(c['key']) is not None:
                    components.append({'wave':c['wave'],'n':c['n'],'outcome':r['v'][c['key']],'mean':c['mean'],'influence':c['sign']*(r['v'][c['key']]-c['mean'])/c['n']})
            rr.append({'index':r['index'],'id':r['id'],'group':r['group'],'components':components,'influence':sum((c['influence'] for c in components),F()) if ok else None})
        result.update(estimate=est,cells=cells,rows=rr,variance=variances(rr) if ok else None)
    return result

"""Standalone continuation attached to by-value Fraction reference functions.
Reads only the three published actual native-field CSVs. No engine, models,
precomputed estimates or another chapter's runtime are read.
"""
import argparse,csv,json,hashlib,html,math
from pathlib import Path
def q(v):return None if v in ('','.') else F(v)
def exact(v):return '' if v is None else str(v)
def read_csv(p):
    with p.open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))
def native_sources(folder):
    people=read_csv(folder/'actual3613-NLS-all52-native-fields.csv');stores=read_csv(folder/'actual410-NJPA-all46-native-fields.csv');wb=read_csv(folder/'actual512-WB-twoindicators-2009-2024.csv')
    assert len(people)==3613 and len(stores)==410 and len(wb)==512
    P=[];D=[];B=[]
    for r in people:
        assert len(r)==53
        parsed={k:q(v)for k,v in r.items()if k!='sourceRow'}
        rid='nls:'+r['id'];P.append({'id':rid,'group':rid,'period':1976,'values':{'wage':exact(parsed['wage76'])or None,'logWage':exact(parsed['lwage76'])or None,'schooling':exact(parsed['ed76'])or None,'age':exact(parsed['age76'])or None},'sourceRow':int(r['sourceRow']),'nativeID':r['id'],'recordedSurveyWeight':r['weight']})
    for r in stores:
        assert len(r)==47
        parsed={k:q(v)for k,v in r.items()if k!='sourceRow'};values={'d':exact(parsed['STATE'])}
        for key,gamma in [('0',F()),('05',F(1,2)),('1',F(1))]:
            vals=[]
            for suffix,wave in [('','before'),('2','after')]:
                c=[parsed[n+suffix]for n in ['EMPFT','EMPPT','NMGRS']];v=None if None in c else c[0]+gamma*c[1]+c[2];values[wave+'FTE'+key]=None if v is None else str(v);vals.append(v)
            values['deltaFTE'+key]=None if None in vals else str(vals[1]-vals[0])
        D.append({'id':'njpa-row:'+r['sourceRow'],'group':'sheet:'+r['SHEET'],'period':1992,'values':values,'sourceRow':int(r['sourceRow']),'nativeSHEET':r['SHEET'],'sourcePostDate':r['DATE2']})
    lookup={}
    for r in wb:
        key=(r['countryISO3'],int(r['year']),r['indicatorID']);assert key not in lookup;lookup[key]=r
    for iso in sorted({r['countryISO3']for r in wb}):
        for year in range(2010,2025):
            g=lookup[iso,year,'NY.GDP.MKTP.KD.ZG'];u=lookup[iso,year,'SL.UEM.TOTL.ZS'];p=lookup[iso,year-1,'SL.UEM.TOTL.ZS'];a,b,c=[q(r['originalValueToken'])for r in [g,u,p]]
            B.append({'id':f'wb:{iso}:{year}','group':'country:'+iso,'period':year,'values':{'growth':exact(a)or None,'unemployment':exact(b)or None,'unemploymentChange':None if b is None or c is None else str(b-c)},'sourceRow':int(g['sourceRow']),'countryISO3':iso,'sourceRows':[int(r['sourceRow'])for r in [g,u,p]]})
    assert len({r['id']for r in P})==3613 and len({r['id']for r in D})==410 and len(B)==240
    return {'person':P,'country':B,'company':D}
def protocols(kind):
    base={'timing':'retrospective-teaching'};out=[]
    def add(name,**d):out.append((name,dict(base,**d)))
    if kind=='person':
        for outcome in ['logWage','wage']:
            unit='1976 nominal cents/hour'if outcome=='wage'else'recorded natural log nominal wage'
            for method in ['mean','ols']:
                name=outcome+('-mean'if method=='mean'else'-schooling-OLS');d={'kind':method,'outcome':outcome,'unit':unit if method=='mean'else unit+' per schooling year','estimand':'declared descriptive '+method+' of '+outcome}
                if method=='ols':d.update(exposure='schooling',controls=[],outcomeUnit=unit,exposureUnit='years of schooling')
                add(name,**d)
    if kind=='country':
        for name,lo,hi in [('2010-2019',2010,2019),('2020-2024',2020,2024),('2010-2024',2010,2024)]:
            for exposure in ['unemployment','unemploymentChange']:add(name+'-'+exposure,kind='ols',outcome='growth',exposure=exposure,controls=[],periodLower=lo,periodUpper=hi,unit='GDP growth percentage points per declared unemployment unit',outcomeUnit='annual GDP growth percent',exposureUnit='unemployment percent'if exposure=='unemployment'else'unemployment annual change percentage points',estimand='descriptive pooled annual GDP growth slope in declared country-year window')
    if kind=='company':
        for frame in ['paired','available']:
            for suffix in ['0','05','1']:add(frame+'-gamma'+suffix,kind='did',groupKey='d',pre='beforeFTE'+suffix,post='afterFTE'+suffix,frame=frame,unit='FTE at gamma '+{'0':'0','05':'1/2','1':'1'}[suffix],estimand='NJ minus PA post-minus-pre finite-sample contrast at declared FTE definition and frame')
    return out
def csv_write(path,rows,headers=None):
    headers=headers or list(rows[0]);
    with path.open('w',encoding='utf8',newline='')as f:
        w=csv.DictWriter(f,fieldnames=headers);w.writeheader()
        for r in rows:w.writerow({k:exact(v)if isinstance(v,F)or v is None else str(v).lower()if isinstance(v,bool)else v for k,v in r.items()})
def finite(value):
    x=float(value);assert math.isfinite(x);return x
def svg_plot(p,points,title,xlabel,ylabel,line=None,language='en',integerX=False,isContrast=False):
    assert points
    X=[finite(a)for a,b in points];Y=[finite(b)for a,b in points];xs=[min(X),max(X)];ys=[min(Y),max(Y)]
    if line:ys += [finite(y)for x,y in line]
    low,high=min(ys),max(ys)
    if xs[0]==xs[1]:xs=[xs[0]-.5,xs[1]+.5]
    if low==high:low-=.5;high+=.5
    dy=(high-low)*.08;low-=dy;high+=dy
    px=lambda x:85+730*(finite(x)-xs[0])/(xs[1]-xs[0]);py=lambda y:390-300*(finite(y)-low)/(high-low)
    esc=lambda s:html.escape(str(s),quote=True)
    annotation=('표시점' if language=='ko' else 'Plot points')+'='+str(len(points))+' · '+(('프로토콜 대비 / 정의 간 연결' if language=='ko' else 'protocol contrasts / definition path') if isContrast else ('관측값 / 기술적 적합' if language=='ko' else 'observations / descriptive fit'))
    out=['<svg xmlns="http://www.w3.org/2000/svg" width="900" height="490" viewBox="0 0 900 490" role="img" aria-label="'+esc(title)+'">','<rect width="900" height="490" fill="#fbfcfe"/>','<g font-family="Noto Sans KR,Arial,sans-serif" fill="#172b40">',f'<text x="85" y="32" font-size="19" font-weight="600">{esc(title)}</text>',f'<text x="85" y="57" font-size="13">{esc(annotation)}</text>']
    for i in range(6):
        yy=low+(high-low)*i/5;cy=py(F(str(yy)));out += [f'<line x1="85" x2="815" y1="{cy:.6f}" y2="{cy:.6f}" stroke="#dce4ed"/>',f'<text x="73" y="{cy+4:.6f}" text-anchor="end" font-size="13">{yy:.5g}</text>']
        xx=xs[0]+(xs[1]-xs[0])*i/5;cx=px(F(str(xx)));out.append(f'<text x="{cx:.6f}" y="417" text-anchor="middle" font-size="13">{xx:.5g}</text>')
    if integerX:
        # Replace only axis tick texts; every original circle and fit stays intact.
        out=[z for z in out if not ('y="417"' in z)]
        step=max(1,math.ceil((xs[1]-xs[0])/5));ticks=list(range(math.ceil(xs[0]),math.floor(xs[1])+1,step))
        if math.floor(xs[1]) not in ticks:ticks.append(math.floor(xs[1]))
        for t in ticks:out.append(f'<text x="{px(F(t)):.6f}" y="417" text-anchor="middle" font-size="13">{t}</text>')
    for x,y in points:out.append(f'<circle cx="{px(x):.9f}" cy="{py(y):.9f}" r="2.2" fill="#275d8d" fill-opacity=".43"/>')
    if line:
        d=' '.join(('M'if i==0 else'L')+f'{px(x):.9f},{py(y):.9f}'for i,(x,y)in enumerate(line));out.append(f'<path d="{d}" fill="none" stroke="#b04b2f" stroke-width="2.5"/>')
    out += [f'<text x="450" y="455" text-anchor="middle" font-size="14">{esc(xlabel)}</text>',f'<text x="85" y="80" font-size="13">{esc(ylabel)}</text>','</g></svg>'];p.write_text('\n'.join(out)+'\n',encoding='utf8')
def main():
    parser=argparse.ArgumentParser(description='METR24 actual-source-only descriptive protocol reproduction; no authentic prospective registration or causal claim.')
    parser.add_argument('--input-dir',type=Path,default=Path('.'));parser.add_argument('--output-dir',type=Path,default=Path('reproduced'));args=parser.parse_args();out=args.output_dir;out.mkdir(parents=True,exist_ok=False)
    data=native_sources(args.input_dir);metrics=[];frames=[];analysis=[];cells=[];components=[];clusters=[];definitions=[];graph=[];summary={};allresults={}
    for kind,rows in data.items():
        rowlookup={r['id']:r for r in rows}
        for name,d in protocols(kind):
            r=ref_plan(rows,d);allresults[kind,name]=r;v=r['variance'];summary[kind+'/'+name]={'sourceRows':len(rows),'eligibleRows':r['eligibleRows'],'estimate':exact(r['estimate'])}
            metrics.append({'kind':kind,'protocol':name,'sourceRows':len(rows),'eligibleRows':r['eligibleRows'],'excludedRows':r['excludedRows'],'estimate':r['estimate'],'unit':d['unit'],'Sxx':r.get('Sxx'),'Sxy':r.get('Sxy'),'SSE':r.get('SSE'),'sampleVariance':r.get('sampleVariance'),'rank':r.get('rank'),'controlRank':r.get('controlRank'),'degreesFreedom':r.get('degreesFreedom'),'rowHC0Variance':None if v is None else v['rowHC0Variance'],'groupHC0Variance':None if v is None else v['groupHC0Variance'],'reportingGroups':None if v is None else v['reportingGroups'],'timing':'retrospective-teaching','automaticPValues':False})
            definitions.append({'kind':kind,'protocol':name,'method':d['kind'],'outcome':d.get('outcome',''),'exposure':d.get('exposure',''),'pre':d.get('pre',''),'post':d.get('post',''),'frame':d.get('frame',''),'periodLower':d.get('periodLower',''),'periodUpper':d.get('periodUpper',''),'unit':d['unit']})
            for i,(row,eligible)in enumerate(zip(rows,r['eligibility'])):
                keys=[d['outcome']]if d['kind']=='mean'else[d['outcome'],d['exposure']]if d['kind']=='ols'else[d['groupKey'],d['pre'],d['post']];missing=[k for k in keys if row['values'].get(k)is None];window=not(d.get('periodLower',-10**9)<=row['period']<=d.get('periodUpper',10**9));reason=''if eligible else'outside-period'if window else'missing-required-variable'
                frames.append({'kind':kind,'protocol':name,'analysisID':row['id'],'sourceRow':row['sourceRow'],'group':row['group'],'period':row['period'],'eligible':eligible,'exclusionReason':reason,'missingRequiredVariables':'|'.join(missing),'nativeID':row.get('nativeID',row.get('nativeSHEET',row.get('countryISO3','')))})
            group_scores={}
            for a in r['rows']:
                row=rowlookup[a['id']];key=a['group'];group_scores[key]=group_scores.get(key,F())+(a['influence']or F())
                analysis.append({'kind':kind,'protocol':name,'analysisID':a['id'],'sourceRow':row['sourceRow'],'group':a['group'],'outcome':q(row['values'].get(d.get('outcome',''))or''),'exposure':q(row['values'].get(d.get('exposure',''))or''),'fitted':a.get('fitted'),'residual':a.get('residual'),'residualExposure':a.get('residualExposure'),'residualOutcome':a.get('residualOutcome'),'linearWeight':a.get('linearWeight'),'influence':a['influence']})
                if kind!='company':
                    xx=q(row['values']['schooling'])if kind=='person'else q(row['values'][d['exposure']]);yy=q(row['values'][d['outcome']]);graph.append({'kind':kind,'chart':name,'analysisID':a['id'],'sourceRow':row['sourceRow'],'x':xx,'y':yy,'fitted':a['fitted']})
                for c in a.get('components',[]):components.append({'kind':kind,'protocol':name,'analysisID':a['id'],'sourceRow':row['sourceRow'],'reportingGroup':a['group'],'wave':c['wave'],'cellN':c['n'],'outcome':c['outcome'],'cellMean':c['mean'],'influence':c['influence']})
            for g,score in group_scores.items():clusters.append({'kind':kind,'protocol':name,'reportingGroup':g,'scoreSum':score,'scoreSquared':score*score})
            for c in r.get('cells',[]):cells.append({'kind':kind,'protocol':name,'state':c['group'],'wave':c['wave'],'n':c['n'],'sum':c['total'],'mean':c['mean'],'contrastSign':c['sign'],'unit':d['unit']})
    for frame in ['paired','available']:
        vals=[allresults['company',frame+'-gamma'+s]['estimate']for s in ['0','05','1']];assert vals[1]==(vals[0]+vals[2])/2
        for gamma,s,v in zip([F(),F(1,2),F(1)],['0','05','1'],vals):graph.append({'kind':'company','chart':frame,'analysisID':frame+'-gamma'+s,'sourceRow':'','x':gamma,'y':v,'fitted':v})
    tables={'protocol-metrics.csv':metrics,'protocol-frame-ledger.csv':frames,'protocol-analysis-rows.csv':analysis,'DID-cell-means.csv':cells,'DID-component-influences.csv':components,'report-group-scores.csv':clusters,'protocol-definitions.csv':definitions,'graph-values.csv':graph};artifacts=[]
    for name,rows in tables.items():
        p=out/name;csv_write(p,rows);artifacts.append({'file':name,'rows':len(rows),'columns':len(rows[0]),'fields':len(rows)*len(rows[0]),'sha256':hashlib.sha256(p.read_bytes()).hexdigest()})
    charts=[]
    for kind in data:
        names=[n for n,d in protocols(kind)]if kind!='company'else['paired','available']
        for name in names:
            rows=[r for r in graph if r['kind']==kind and r['chart']==name];points=[(r['x'],r['y'])for r in rows]
            ordered=sorted(rows,key=lambda r:r['x']);line=[(ordered[0]['x'],ordered[0]['fitted']),(ordered[-1]['x'],ordered[-1]['fitted'])]if kind!='company'else[(r['x'],r['fitted'])for r in ordered]
            for L in ['ko','en']:
                title=({'person':'개인','country':'국가','company':'기업'}[kind]if L=='ko'else kind.title())+' · '+name
                xlabel='교육 연수'if L=='ko'and kind=='person'else'Schooling years'if kind=='person'else'실업 수준 %'if L=='ko'and kind=='country'and name.endswith('-unemployment')else'실업 변화 %포인트'if L=='ko'and kind=='country'else'Unemployment percent'if kind=='country'and name.endswith('-unemployment')else'Unemployment change pp'if kind=='country'else'시간제 인원 계수 gamma'if L=='ko'else'Part-time coefficient gamma'
                ylabel='1976 cents/hour'if kind=='person'and name.startswith('wage-')else'Recorded log wage'if kind=='person'else'Annual GDP growth percent'if kind=='country'else'DID in gamma-specific FTE'
                filename=kind+'-'+name+'-'+L+'.svg'
                if L=='ko':ylabel='1976년 명목 센트/시간'if kind=='person'and name.startswith('wage-')else'기록 로그 임금'if kind=='person'else'연간 GDP 성장률 %'if kind=='country'else'정의 gamma의 FTE DID'
                svg_plot(out/filename,points,title,xlabel,ylabel,line,language=L,integerX=kind=='person',isContrast=kind=='company');charts.append({'kind':kind,'chart':name,'language':L,'file':filename,'points':len(points)})
    report={'chapter':'METR-24','status':'Actual-source-only reproduction completed','scope':'Unit-weight descriptive protocols; previously viewed retained data. No source p-values, genuine prospective preregistration or causal certificate. Python exact rational arithmetic is not measurement-error certification.','protocols':summary,'CSV':artifacts,'fields':sum(x['fields']for x in artifacts),'charts':charts,'graphPointsPerLanguage':len(graph),'sourceFiles':[{'file':p,'sha256':hashlib.sha256((args.input_dir/p).read_bytes()).hexdigest()}for p in ['actual3613-NLS-all52-native-fields.csv','actual410-NJPA-all46-native-fields.csv','actual512-WB-twoindicators-2009-2024.csv']]}
    (out/'source-reproduction.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n',encoding='utf8');print(json.dumps({'status':report['status'],'protocols':len(summary),'CSV':len(artifacts),'fields':report['fields'],'SVG':len(charts),'graphPointsPerLanguage':len(graph)}))
if __name__=='__main__':main()
