"""STAT-23: actual finite-law moments and conditional decomposition.
Actual data are read again; case JSON and prior results are not numeric inputs.
Python standard library only; no original data or recorded mass is overwritten.
"""
from pathlib import Path
from fractions import Fraction as Q
from decimal import Decimal as D,getcontext
from collections import Counter
from html.parser import HTMLParser
import csv,hashlib,json,re,io,zipfile,math,itertools
import xml.etree.ElementTree as ET
getcontext().prec=110
ROOT=Path(__file__).resolve().parent;WORKSPACE=ROOT.parents[1]
COMMON=ROOT/'\uc2e4\uc81c\ub370\uc774\ud130';DATA=ROOT/'stats23-sources'
METRICS={};EXACT={};AUDIT=[];CHECKS={'selectedValuesCompared':0}
def read(path):
    with path.open(encoding='utf-8-sig',newline='') as stream:return list(csv.DictReader(stream))
def note(path,purpose,original=False):AUDIT.append({'file':str(path.relative_to(ROOT)) if path.is_relative_to(ROOT) else str(path.relative_to(WORKSPACE)),'sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'purpose':purpose,'archivedOriginalUsed':original})
APPROX=[]
def add(key,value):
    METRICS[key]=float(value)
    if isinstance(value,(Q,int)):EXACT[key]=str(Q(value))
    else:APPROX.append(key)
def near(a,b):assert abs(float(a)-float(Q(b)))<=1e-10*max(1,abs(float(a))),(a,b)
def same(value,stored):assert value==Q(stored),(value,stored);CHECKS['selectedValuesCompared']+=1




def field(line,a,b):
    s=line[a-1:b].strip();return None if s in ['','.'] else Q(s)
raw=WORKSPACE/'work/textbooks-2026/raw';W=read(COMMON/'worldbank.csv');note(COMMON/'worldbank.csv','actual retained country-year observations');originalfile=raw/'worldbank-panel.json'
if originalfile.is_file():
    note(originalfile,'original World Bank API response',True);original=json.loads(originalfile.read_text(encoding='utf-8'),parse_float=D)[1];lookup={(r['countryiso3code'],r['date'],r['indicator']['id']):r['value'] for r in original};assert len(original)==6480
    for r in W:
        for key,code in [('gdp_pc','NY.GDP.PCAP.KD'),('life_expectancy','SP.DYN.LE00.IN')]:
            v=lookup[(r['country'],r['year'],code)]
            if v is None:assert r[key]==''
            else:same(Q(v),r[key])
countries=sorted([r for r in W if r['year']=='2024'],key=lambda r:r['country']);assert len(countries)==16
C=read(COMMON/'college-proximity.csv');note(COMMON/'college-proximity.csv','retained actual people with missingness');archive=raw/'proximity.zip';spec=[('person',1,5),('nearc4',10,10),('education',18,19),('age',24,25),('log_wage',86,97),('metro',116,116),('south',120,120)]
if archive.is_file():
    note(archive,'original Card fixed-width person observations',True)
    with zipfile.ZipFile(archive) as z:lines=z.read('nls.dat').decode('ascii').splitlines()
    assert len(lines)==len(C)==3613;people=[{k:field(line,a,b) for k,a,b in spec} for line in lines]
    for o,r in zip(people,C):
        for k,a,b in spec:
            if o[k] is None:assert r[k]==''
            else:same(o[k],r[k])
else:people=[{k:Q(r[k]) if r[k] else None for k,a,b in spec} for r in C]
w=[r['log_wage'] for r in people if r['log_wage'] is not None];assert len(w)==3010
NJ=read(COMMON/'nj-minwage.csv');note(COMMON/'nj-minwage.csv','actual stores retaining both waves and missingness');archive=raw/'njmin.zip';spec=[('store',1,3),('chain',5,5),('nj',9,9),('ft_before',26,30),('pt_before',32,36),('managers_before',38,42),('wage_before',44,48),('status_after',110,110),('ft_after',122,126),('pt_after',128,132),('managers_after',134,138),('wage_after',140,144)]
if archive.is_file():
    note(archive,'original Card/Krueger fixed-width store observations',True)
    with zipfile.ZipFile(archive) as z:lines=z.read('public.dat').decode('ascii').splitlines();sas=z.read('check.sas').decode('latin1')
    assert len(lines)==len(NJ)==410 and 'EMPPT*.5 + EMPFT + NMGRS' in sas;stores=[{k:field(line,a,b) for k,a,b in spec} for line in lines]
    for o,r in zip(stores,NJ):
        for k,a,b in spec:
            if o[k] is None:assert r[k]==''
            else:same(o[k],r[k])
else:stores=[{k:Q(r[k]) if r[k] else None for k,a,b in spec} for r in NJ]
for o,r in zip(stores,NJ):
    for s in ['before','after']:
        ks=['ft_'+s,'pt_'+s,'managers_'+s];o['fte_'+s]=o[ks[0]]+o[ks[1]]/2+o[ks[2]] if all(o[k] is not None for k in ks) else None
        if o['fte_'+s] is None:assert r['fte_'+s]==''
        else:same(o['fte_'+s],r['fte_'+s])

def avg(v):return sum(v,Q(0))/len(v)
Y=[Q(o['gdp_pc']) for o in countries];G=[int(Q(o['life_expectancy'])>=80) for o in countries];target=avg(Y)
path=DATA/'actual16-complete-country-GDP-and-life-data.csv';S=read(path);note(path,'actual complete2024 GDP/life values')
for o,r,g in zip(countries,S,G):assert o['country']==r['country'];same(Q(o['gdp_pc']),r['actual2024_GDPpc_constant2015USD_person']);same(Q(o['life_expectancy']),r['actual2024_period_life_years']);same(Q(g),r['derived_life_ge80'])
path=DATA/'explicit-response-law-probabilities-and-expected-contributions.csv';L=read(path);note(path,'explicitly imposed response probabilities and exact expected contributions');path=DATA/'explicit-response-law-exact-conditional-and-IPW-means.csv';S=read(path);note(path,'exact conditional respondent means, not finite expected ratios')
for name in ['chosen_MCAR_half','chosen_MAR_life_group','chosen_MNAR_GDP_threshold']:
 rates=[Q(1,2) if name=='chosen_MCAR_half' else Q(1,4)+Q(1,2)*int(g if name=='chosen_MAR_life_group' else y>=30000) for y,g in zip(Y,G)];gr={g:avg([rate for rate,label in zip(rates,G) if label==g]) for g in [0,1]};response=avg(rates);observed=sum((rate*y for rate,y in zip(rates,Y)),Q(0))/sum(rates,Q(0));correct=avg([rate*y/rate for rate,y in zip(rates,Y)]);groupIPW=avg([rate*y/gr[g] for rate,y,g in zip(rates,Y,G)]);assert correct==target
 for o,y,g,rate in zip(countries,Y,G,rates):
  r=next(r for r in L if r['chosen_response_law']==name and r['country']==o['country']);vals=dict(true_assumed_response_probability_exact=rate,life_group_marginal_response_probability_exact=gr[g],response_times_GDP_contribution_exact=rate*y,correct_inverse_response_weighted_expected_contribution_exact=y,life_group_only_weighted_expected_contribution_exact=rate*y/gr[g])
  for key,v in vals.items():same(v,r[key])
 r=next(r for r in S if r['chosen_response_law']==name);vals=dict(known_actual_frame_mean_exact=target,assumed_response_probability_exact=response,assumed_conditional_respondent_mean_exact=observed,respondent_mean_minus_actual_frame_mean_exact=observed-target,known_true_probability_IPW_expected_mean_exact=correct,life_group_only_IPW_expected_mean_exact=groupIPW,life_group_only_IPW_expected_bias_exact=groupIPW-target,actual_missing_country_GDP_in_source=Q(0))
 for key,v in vals.items():same(v,r[key]);add('country_'+name+'_'+key,v)
path=DATA/'chosen-MAR-response-probability-sensitivity.csv';S=read(path);note(path,'nine hypothetical response laws on unchanged actual GDP')
for i,r in enumerate(S,1):
 hi=Q(i,10);rates=[hi if g else Q(1,2) for g in G];observed=sum((rate*y for rate,y in zip(rates,Y)),Q(0))/sum(rates,Q(0));vals=dict(chosen_response_probability_life_ge80_exact=hi,chosen_response_probability_life_lt80_exact=Q(1,2),conditional_respondent_GDP_mean_exact=observed,known_full_frame_GDP_mean_exact=target,exact_known_response_IPW_expectation_exact=target)
 for key,v in vals.items():same(v,r[key]);add('country_MARprofile'+str(i)+'_'+key,v)
path=DATA/'actual3613-people-source-log-missingness-and-schooling.csv';S=read(path);note(path,'actual source logs, schooling and unavailable603 preserved')
for i,(o,r) in enumerate(zip(people,S),1):
 same(Q(i),r['sourceRow']);same(o['person'],r['source_person_code']);same(o['education'],r['actual_education_years']);assert (r['log_available']=='True')==(o['log_wage'] is not None)
 if o['log_wage'] is None:assert r['source_trimmed1976_log_hourly_wage_cents']==''
 else:same(o['log_wage'],r['source_trimmed1976_log_hourly_wage_cents'])
ps=[]
for flag in [False,True]:
 rows=[o for o in people if (o['education']>12)==flag];ys=[o['log_wage'] for o in rows if o['log_wage'] is not None];ps.append(dict(all_source_rows=len(rows),available_logs=len(ys),unavailable_logs=len(rows)-len(ys),available_log_sum_exact=sum(ys,Q(0)),available_log_mean_exact=avg(ys),observed_availability_fraction_exact=Q(len(ys),len(rows))))
path=DATA/'actual-schooling-group-log-availability-and-sums.csv';S=read(path);note(path,'actual group-specific denominators independently summed')
for group,(o,r) in enumerate(zip(ps,S)):
 for key,v in o.items():same(Q(v),r[key]);add('person_group'+str(group)+'_'+key,v)
logs=[o['log_wage'] for o in people if o['log_wage'] is not None];NP=len(people);missing=NP-len(logs);observed=avg(logs);total=sum(logs,Q(0));path=DATA/'assumed-missing-log-mean-offset-sensitivity.csv';S=read(path);note(path,'eleven assumed pattern-mixture means, no actual value recovery')
for i,r in enumerate(S):
 delta=Q(i-5,10);full=sum((Q(g['available_log_sum_exact'])+g['unavailable_logs']*(Q(g['available_log_mean_exact'])+delta) for g in ps),Q(0))/NP;vals=dict(assumed_common_missing_minus_observed_group_log_mean_exact=delta,assumed_full3613_log_mean_exact=full,actual_available3010_log_mean_exact=observed,assumed_full_mean_minus_available_mean_exact=full-observed)
 for key,v in vals.items():same(v,r[key]);add('person_sensitivity'+str(i)+'_'+key,v)
path=DATA/'explicit-unobserved-log-range-and-partial-mean-bounds.csv';S=read(path);note(path,'explicitly chosen missing-log range and exact conditional bounds');vals=dict(chosen_missing_log_lower_exact=Q(4),chosen_missing_log_upper_exact=Q(9),available_sum_exact=total,actual_unavailable_count=Q(missing),assumed_full_mean_lower_bound_exact=(total+missing*4)/NP,assumed_full_mean_upper_bound_exact=(total+missing*9)/NP)
for key,v in vals.items():same(v,S[0][key]);add('person_'+key,v)
path=DATA/'actual410-source-row-preserving-two-wave-FTE-and-missingness.csv';S=read(path);note(path,'same-row components preserve source407 rows42/168,26 incomplete pairs')
ss=[]
for i,(o,r) in enumerate(zip(stores,S),1):
 same(Q(i),r['source_row_id']);same(o['store'],r['original_nonunique_store_code']);same(o['chain'],r['actual_chain']);assert r['state']==('NJ' if o['nj']==1 else 'PA');complete=o['fte_before'] is not None and o['fte_after'] is not None;assert (r['complete_pair']=='True')==complete
 for key,v in [('actual_before_FTE',o['fte_before']),('actual_after_FTE',o['fte_after']),('observed_paired_FTE_change',o['fte_after']-o['fte_before'] if complete else None)]:
  if v is None:assert r[key]==''
  else:same(v,r[key])
for flag in [1,0]:
 rows=[o for o in stores if o['nj']==flag];ys=[o['fte_after']-o['fte_before'] for o in rows if o['fte_after'] is not None and o['fte_before'] is not None];ss.append(dict(all_original_rows=len(rows),available_before_FTE=sum(o['fte_before'] is not None for o in rows),available_after_FTE=sum(o['fte_after'] is not None for o in rows),complete_pairs=len(ys),incomplete_pairs=len(rows)-len(ys),complete_pair_change_sum_exact=sum(ys,Q(0)),complete_pair_change_mean_exact=avg(ys),incomplete_fraction_exact=Q(len(rows)-len(ys),len(rows))))
path=DATA/'actual-state-specific-component-availability-and-paired-changes.csv';S=read(path);note(path,'actual state denominators and paired changes')
for name,(o,r) in zip(['NJ','PA'],zip(ss,S)):
 for key,v in o.items():same(Q(v),r[key]);add('company_'+name+'_'+key,v)
nj,pa=ss;gap=nj['complete_pair_change_mean_exact']-pa['complete_pair_change_mean_exact'];nf=nj['incomplete_fraction_exact'];pf=pa['incomplete_fraction_exact'];path=DATA/'assumed-incomplete-pair-change-mean-sensitivity-grid.csv';S=read(path);note(path,'25 assumed missing-change mean scenarios, not policy effects')
for i,((dn,dp),r) in enumerate(zip(itertools.product([Q(-10),Q(-5),Q(0),Q(5),Q(10)],repeat=2),S)):
 mn=nj['complete_pair_change_mean_exact']+nf*dn;mp=pa['complete_pair_change_mean_exact']+pf*dp;full=(nj['all_original_rows']*mn+pa['all_original_rows']*mp)/410;vals=dict(assumed_NJ_missing_minus_complete_change_mean_FTE_exact=dn,assumed_PA_missing_minus_complete_change_mean_FTE_exact=dp,assumed_full_NJ_change_mean_FTE_exact=mn,assumed_full_PA_change_mean_FTE_exact=mp,assumed_full_NJ_minus_PA_observed_change_contrast_FTE_exact=mn-mp,assumed_full410_change_mean_FTE_exact=full)
 for key,v in vals.items():same(v,r[key]);add('company_sensitivity'+str(i)+'_'+key,v)
path=DATA/'assumed-zero-state-contrast-tipping-offsets.csv';S=read(path);note(path,'algebraic tipping offsets conditional on missing-mean model')
for i,(dp,r) in enumerate(zip([Q(-10),Q(0),Q(10)],S)):
 tipping=(pf*dp-gap)/nf;assert gap+nf*tipping-pf*dp==0;vals=dict(held_PA_missing_minus_complete_change_mean_FTE_exact=dp,NJ_offset_for_zero_full_state_change_contrast_FTE_exact=tipping,actual_complete_pair_state_change_contrast_FTE_exact=gap,NJ_incomplete_fraction_exact=nf,PA_incomplete_fraction_exact=pf)
 for key,v in vals.items():same(v,r[key]);add('company_tipping'+str(i)+'_'+key,v)
CHECKS['actual603MissingLogsAnd26IncompletePairsPreserved']=True;CHECKS['assumedResponseAndMissingMeanLawsNotObservedFacts']=True

rpath=ROOT/'stat23-r-results.csv'
if rpath.is_file():
 R={r['metric']:float(r['value']) for r in read(rpath)};assert set(R)==set(METRICS)
 for key,value in METRICS.items():
  near(value,R[key])
  if 0<abs(value)<1e-9:assert abs(R[key]/value-1)<=1e-8,(key,R[key],value)
 CHECKS['RmetricComparisons']=len(METRICS)
else:CHECKS['RmetricComparisons']=0
for item in AUDIT:
 path=ROOT/item['file']
 if not path.is_file():path=WORKSPACE/item['file']
 assert hashlib.sha256(path.read_bytes()).hexdigest()==item['sha256']
CHECKS['inputHashesPreserved']=len(AUDIT)
CHECKS['caseJSONOrPreviousMetricsUsedAsNumericInputs']=False
(ROOT/'stat23-results.json').write_text(json.dumps(dict(chapter='STAT-23',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,interpretation='Original public observations are numeric inputs. Country data are actually complete; imposed response laws are exact teaching experiments. Conditional respondent means are not asserted as expectations of finite random ratios. Person603 unavailable logs and store26 incomplete pairs remain missing; pattern-mixture offsets and range bounds are explicit assumptions, not observed recovery, actual mechanism identification, confidence intervals or causal policy effects.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('STAT-23:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
