"""DATA-01: 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/'data01-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])

# Actual source quantities, not any case JSON or previous metric file.
def avg(v):return sum(v,Q(0))/len(v)
source_positions={(r['countryiso3code'],r['date'],r['indicator']['id']):i for i,r in enumerate(original,1)} if originalfile.is_file() else {}
records={
 'country':[dict(sourceRow=source_positions.get((r['country'],'2024','NY.GDP.PCAP.KD')),code=r['country'],group='life_ge_80' if Q(r['life_expectancy'])>=80 else 'life_lt_80',value=Q(r['gdp_pc']),life=Q(r['life_expectancy'])) for r in countries],
 'person':[dict(sourceRow=i,code=str(int(o['person'])),group='schooling_le12' if o['education']<=12 else 'schooling_gt12',value=o['log_wage'],schooling=o['education']) for i,o in enumerate(people,1)],
 'company':[dict(sourceRow=i,code=str(int(o['store'])),group='NJ' if o['nj']==1 else 'PA',value=o['fte_after']-o['fte_before'] if o['fte_after'] is not None and o['fte_before'] is not None else None,before=o['fte_before'],after=o['fte_after'],chain=o['chain']) for i,o in enumerate(stores,1)]
}
names={'country':'actual16-country-2024-records-and-original-API-row-keys.csv','person':'actual3613-person-records-and-unavailable-source-logs.csv','company':'actual410-two-wave-store-records-and-unique-original-row-keys.csv'}
for kind,rows in records.items():
 path=DATA/names[kind];S=read(path);note(path,'actual selected records and original positional keys checked against source');assert len(rows)==len(S)
 for o,r in zip(rows,S):
  assert o['code']==r['code'] and o['group']==r['group']
  if o['sourceRow'] is not None:same(Q(o['sourceRow']),r['sourceRow'])
  for key in ['value']+(['before','after'] if kind=='company' else []):
   if o[key] is None:assert r[key]==''
   else:same(o[key],r[key])
  if kind=='country':same(o['life'],r['lifeExpectancy'])
  if kind=='person':same(o['schooling'],r['schooling'])
  if kind=='company':same(o['chain'],r['chain'])
 add(kind+'_all_original_records',len(rows));add(kind+'_available_values',sum(o['value'] is not None for o in rows));add(kind+'_unavailable_values',sum(o['value'] is None for o in rows))
path=DATA/'actual-record-denominators-and-explicit-target-rules.csv';S=read(path);note(path,'all available-value denominators and explicit weighting targets recalculated')
assert len(S)==9
for kind,groups in [('country',['life_ge_80','life_lt_80']),('person',['schooling_le12','schooling_gt12']),('company',['NJ','PA'])]:
 rs=records[kind];groupmu=[avg([o['value'] for o in rs if o['group']==g and o['value'] is not None]) for g in groups];equalgroups=avg(groupmu)
 for group in ['ALL']+groups:
  rows=rs if group=='ALL' else [o for o in rs if o['group']==group];ys=[o['value'] for o in rows if o['value'] is not None];r=next(r for r in S if r['case']==kind and r['group']==group)
  vals=dict(source_records=len(rows),available_value_records=len(ys),unavailable_value_records=len(rows)-len(ys),available_value_sum_exact=sum(ys,Q(0)),available_value_mean_exact=avg(ys),availability_fraction_exact=Q(len(ys),len(rows)),equal_group_mean_of_available_values_exact=equalgroups)
  for key,value in vals.items():same(Q(value),r[key]);add(kind+'_'+group+'_'+key,value)
rows=records['company'];code407=[o for o in rows if o['code']=='407'];path=DATA/'actual-repeated-store-code407-two-distinct-source-rows.csv';S=read(path);note(path,'both code407 rows kept with distinct original record keys');assert len(code407)==len(S)==2
for o,r in zip(code407,S):
 same(Q(o['sourceRow']),r['sourceRow']);assert o['group']==r['group'];same(o['chain'],r['chain']);same(o['value'],r['value']);add('original_code407_row'+str(o['sourceRow'])+'_observed_change',o['value'])
add('stores_distinct_original_codes',len(set(o['code'] for o in rows)));add('stores_unique_source_row_keys',len(set(o['sourceRow'] for o in rows)))
paired=[o for o in rows if o['value'] is not None];before=[o['before'] for o in paired];after=[o['after'] for o in paired];bm=avg(before);am=avg(after);bmse=avg([(v-bm)**2 for v in after]);amse=avg([(v-am)**2 for v in after]);assert bmse-amse==(bm-am)**2
path=DATA/'actual-complete-pairs-before-constant-and-after-oracle-loss.csv';S=read(path);note(path,'same384 observed pairs and test-label oracle comparison, not validated future performance');assert len(S)==1
vals=dict(complete_original_row_pairs=len(paired),before_mean_exact=bm,after_mean_exact=am,future_after_MSE_using_before_constant_exact=bmse,after_test_mean_oracle_MSE_exact=amse,gap_equals_squared_mean_shift_exact=(bm-am)**2)
for key,value in vals.items():same(Q(value),S[0][key]);add('stores_'+key,value)

rpath=ROOT/'data01-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/'data01-results.json').write_text(json.dumps(dict(chapter='DATA-01',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,interpretation='Original public observations and retained source cells are numeric inputs, not case JSON or prior metrics. Available-value weighting targets are explicit choices, not representative-population estimates. Unavailable source values are never zero filled. Store407 original rows42/168 are distinct traceable records. Before-constant/after-oracle loss is an in-data information-timing illustration, not certified future performance or causal policy evidence.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('DATA-01:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
