"""DATA-08: 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/'data08-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)
def verify(name,expected):
 path=DATA/name;S=read(path);note(path,'original records and selected summaries independently reconstructed');assert len(S)==len(expected),(name,len(S),len(expected))
 for row,o in zip(S,expected):
  assert set(row)==set(o),(name,set(row),set(o))
  for k,v in o.items():
   if v is None:assert row[k]=='',(name,k,row[k])
   elif isinstance(v,bool):assert row[k]==str(v)
   elif isinstance(v,(Q,int)):same(Q(v),row[k])
   elif isinstance(v,float):near(v,row[k])
   else:assert row[k]==str(v),(name,k,row[k],v)
 return S
position={(r['countryiso3code'],r['date'],r['indicator']['id']):i for i,r in enumerate(original,1)} if originalfile.is_file() else {}
selected=sorted([r for r in W if r['country']=='KOR' and 2000<=int(r['year'])<=2024],key=lambda r:int(r['year']));baseg=Q(selected[0]['gdp_pc']);basel=Q(selected[0]['life_expectancy']);time=[]
for r in selected:time.append(dict(country_ISO='KOR',year=int(r['year']),GDP_source_API_row=position.get(('KOR',r['year'],'NY.GDP.PCAP.KD')),life_source_API_row=position.get(('KOR',r['year'],'SP.DYN.LE00.IN')),actual_GDPpc_constant2015USD_source_decimal=r['gdp_pc'],actual_period_life_years_source_decimal=r['life_expectancy'],chosen_GDPpc_index2000eq100_exact=Q(r['gdp_pc'])/baseg*100,chosen_life_index2000eq100_exact=Q(r['life_expectancy'])/basel*100))
if not position:
 for r,s in zip(time,read(DATA/'actual25-Korea-annual-indicators-and-chosen-rebased-displays.csv')):r['GDP_source_API_row']=int(s['GDP_source_API_row']);r['life_source_API_row']=int(s['life_source_API_row'])
verify('actual25-Korea-annual-indicators-and-chosen-rebased-displays.csv',time)
for r in time:
 for k in ['actual_GDPpc_constant2015USD_source_decimal','actual_period_life_years_source_decimal','chosen_GDPpc_index2000eq100_exact','chosen_life_index2000eq100_exact']:add('country_year'+str(r['year'])+'_'+k,Q(r[k]))
differences=[dict(country_ISO='KOR',earlier_year=a['year'],later_year=c['year'],GDPpc_difference_constant2015USD_per_person_exact=Q(c['actual_GDPpc_constant2015USD_source_decimal'])-Q(a['actual_GDPpc_constant2015USD_source_decimal']),period_life_difference_years_exact=Q(c['actual_period_life_years_source_decimal'])-Q(a['actual_period_life_years_source_decimal'])) for a,c in zip(time,time[1:])];verify('actual24-adjacent-Korea-annual-differences.csv',differences)
for r in differences:
 for k in ['GDPpc_difference_constant2015USD_per_person_exact','period_life_difference_years_exact']:add('country_difference'+str(r['later_year'])+'_'+k,r[k])
cross=[dict(country_ISO=r['country'],year=2024,actual_GDPpc_constant2015USD_source_decimal=r['gdp_pc'],actual_period_life_years_source_decimal=r['life_expectancy']) for r in countries];verify('actual16-country-same2024-indicator-pairs.csv',cross)
def summary(label,x,y,ux,uy):
 mx=avg(x);my=avg(y);xx=sum(((v-mx)**2 for v in x),Q(0));yy=sum(((v-my)**2 for v in y),Q(0));xy=sum(((a-mx)*(c-my) for a,c in zip(x,y)),Q(0));r2=xy**2/(xx*yy);r=math.copysign(math.sqrt(float(r2)),xy);return dict(view=label,n=len(x),x_units=ux,y_units=uy,x_mean_exact=mx,y_mean_exact=my,centered_cross_sum_exact=xy,centered_x_square_sum_exact=xx,centered_y_square_sum_exact=yy,Pearson_r_squared_exact=r2,Pearson_r_binary64_approx=r)
correlations=[summary('selected16_countries_same2024',[Q(r['actual_GDPpc_constant2015USD_source_decimal']) for r in cross],[Q(r['actual_period_life_years_source_decimal']) for r in cross],'constant2015USD/person','period_life_years'),summary('KOR25_annual_levels2000to2024',[Q(r['actual_GDPpc_constant2015USD_source_decimal']) for r in time],[Q(r['actual_period_life_years_source_decimal']) for r in time],'constant2015USD/person','period_life_years'),summary('KOR24_adjacent_annual_differences',[r['GDPpc_difference_constant2015USD_per_person_exact'] for r in differences],[r['period_life_difference_years_exact'] for r in differences],'constant2015USD/person_difference','period_life_year_difference')];verify('three-different-observational-relationship-summaries.csv',correlations)
for i,r in enumerate(correlations):
 for k,v in r.items():
  if k not in ['view','x_units','y_units']:add('country_relationship'+str(i)+'_'+k,v)
persons=[dict(source_row_id=i,source_person_code=str(int(o['person'])),recorded_education_years=C[i-1]['education'],source_trimmed_log1976_hourly_cents_source_decimal=C[i-1]['log_wage'],source_metro_code=C[i-1]['metro'],source_south_code=C[i-1]['south']) for i,o in enumerate(people,1)];verify('actual3613-person-education-and-source-logs-missing-preserved.csv',persons)
groups=[]
for level in sorted({o['education'] for o in people}):
 rows=[o for o in people if o['education']==level];ys=[o['log_wage'] for o in rows if o['log_wage'] is not None];groups.append(dict(education_years_exact=level,all_source_records=len(rows),available_log_records=len(ys),unavailable_log_records=len(rows)-len(ys),available_log_sum_exact=sum(ys,Q(0)),available_log_mean_exact=avg(ys) if ys else None,available_log_min_exact=min(ys) if ys else None,available_log_max_exact=max(ys) if ys else None))
verify('actual19-education-level-log-wage-summaries.csv',groups)
for i,r in enumerate(groups):
 for k,v in r.items():
  if v is not None:add('person_group'+str(i)+'_'+k,v)
values=[o['log_wage'] for o in people if o['log_wage'] is not None];groupmeans=[r['available_log_mean_exact'] for r in groups if r['available_log_mean_exact'] is not None];ps=dict(all_source_records=len(people),available_log_records=len(values),unavailable_log_records=len(people)-len(values),recorded_education_levels=len(groups),levels_with_available_logs=len(groupmeans),pooled_available_log_mean_exact=avg(values),equal_available_education_group_mean_exact=avg(groupmeans));verify('person-pooled-versus-equal-education-group-targets.csv',[ps])
for k,v in ps.items():add('person_'+k,v)
expected=[dict(source_row_id=i,original_store_code=str(int(o['store'])),state='NJ' if o['nj']==1 else 'PA',chain_code=str(int(o['chain'])),actual_before_FTE_source_decimal=NJ[i-1]['fte_before'],actual_after_FTE_source_decimal=NJ[i-1]['fte_after'],same_source_row_change_FTE_exact=o['fte_after']-o['fte_before'] if o['fte_after'] is not None and o['fte_before'] is not None else None) for i,o in enumerate(stores,1)];verify('actual410-two-wave-stores-same-source-row-preserved.csv',expected);ss=[]
for state in ['PA','NJ']:
 rows=[o for o in stores if ('NJ' if o['nj']==1 else 'PA')==state];bv=[o['fte_before'] for o in rows if o['fte_before'] is not None];av=[o['fte_after'] for o in rows if o['fte_after'] is not None];pairs=[o for o in rows if o['fte_before'] is not None and o['fte_after'] is not None];bp=[o['fte_before'] for o in pairs];ap=[o['fte_after'] for o in pairs];row=dict(state=state,all_source_records=len(rows),before_available_records=len(bv),after_available_records=len(av),complete_same_source_row_pairs=len(pairs),before_all_available_mean_FTE_exact=avg(bv),after_all_available_mean_FTE_exact=avg(av),unpaired_available_mean_difference_FTE_exact=avg(av)-avg(bv),before_paired_mean_FTE_exact=avg(bp),after_paired_mean_FTE_exact=avg(ap),paired_mean_change_FTE_exact=avg(ap)-avg(bp),difference_due_to_different_retained_sets_FTE_exact=avg(av)-avg(bv)-avg(ap)+avg(bp));assert avg([o['fte_after']-o['fte_before'] for o in pairs])==row['paired_mean_change_FTE_exact'];ss.append(row)
verify('actual-two-state-available-versus-complete-pair-summaries.csv',ss)
for r in ss:
 for k,v in r.items():
  if k!='state':add('company_'+r['state']+'_'+k,v)
CHECKS.update(annualTimeOrderPreserved=True,differentOriginalUnitsExplicit=True,displayRebasingNotNewObservedSeries=True,schoolingGroupRangesNotConfidenceIntervals=True,unavailableValuesNotZeroFilled=True,sourceRow407BothRecordsKept=True,pairMeanDifferenceIdentityExact=True,associationIsNotIdentifiedCausalEffect=True)

rpath=ROOT/'data08-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/'data08-results.json').write_text(json.dumps(dict(chapter='DATA-08',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,interpretation='Actual original public observations supply all numeric inputs. Distinct country cross sections, Korean levels/differences, schooling groups and same-record establishment changes answer different questions. Rebasing is explicit display processing. No case JSON supplies metrics. Undefined means remain unavailable; group ranges are not confidence intervals. Identical pairs preserve exact mean-change identity; available wave sets can differ. No independence or causal policy/schooling effect is inferred.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('DATA-08:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
