"""DATA-02: 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/'data02-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])

import platform,sys
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((o['country'],'2024','NY.GDP.PCAP.KD')),code=o['country'],value=Q(o['gdp_pc']),sourceText=o['gdp_pc']) for o in countries],
 'person':[dict(sourceRow=i,code=str(int(o['person'])),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',chain=str(int(o['chain'])),before=o['fte_before'],after=o['fte_after'],value=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)]
}
paths={'country':'actual16-country-source-keys-text-values-and-unit-conversion.csv','person':'actual3613-person-source-text-and-availability.csv','company':'actual410-store-source-keys-two-waves-and-availability.csv'}
for kind,rows in records.items():
 path=DATA/paths[kind];S=read(path);note(path,'actual source keys, labels, decimal values and missingness reconstructed from original');assert len(S)==len(rows)
 for o,r in zip(rows,S):
  assert r['code']==o['code'] and isinstance(o['code'],str)
  if o['sourceRow'] is not None:same(Q(o['sourceRow']),r['sourceRow'])
  assert (r['valueAvailable']=='True')==(o['value'] is not None)
  if kind=='country':assert r['yearText']=='2024' and r['indicatorCode']=='NY.GDP.PCAP.KD';same(o['value'],r['valueSourceText']);same(o['value'],r['valueExactFraction']);same(o['value']/10000,r['scaledDiv10000Exact'])
  elif kind=='person':
   same(o['schooling'],r['schoolingSourceText'])
   if o['value'] is None:assert r['valueSourceText']==''
   else:same(o['value'],r['valueSourceText'])
  else:
   assert o['group']==r['group'] and o['chain']==r['chainCodeText']
   for key,value in [('beforeSourceText',o['before']),('afterSourceText',o['after']),('valueExactFraction',o['value'])]:
    if value is None:assert r[key]==''
    else:same(value,r[key])
path=DATA/'actual-record-summaries-and-deliberately-invalid-zero-fill-comparison.csv';S=read(path);note(path,'valid-denominator exact summary and explicitly invalid zero-fill comparison')
def summary_present(values):
 good=[x for x in values if x is not None]
 return {'n_total':len(values),'n_valid':len(good),'mean':sum(good)/len(good) if good else None}
runtime={}
for kind,rows in records.items():
 xs=[o['value'] for o in rows];good=[x for x in xs if x is not None];total=sum(good,Q(0));mean=total/len(good);r=next(r for r in S if r['case']==kind);values=dict(allRows=Q(len(xs)),availableRows=Q(len(good)),unavailableRows=Q(len(xs)-len(good)),availableSumExact=total,availableMeanExact=mean,unavailableZeroFilledMeanExact=total/len(xs))
 for key,value in values.items():same(value,r[key]);add(kind+'_'+key,value)
 actual=summary_present([float(x) if x is not None else None for x in xs]);near(actual['mean'],mean);assert actual['n_total']==len(xs) and actual['n_valid']==len(good);add(kind+'_native_function_float_mean',actual['mean']);runtime[kind]={'inputContainerType':'list','nonmissingValueType':'float','missingValueType':'NoneType','resultContainerType':type(actual).__name__,'result':actual}
empty=summary_present([]);assert empty==dict(n_total=0,n_valid=0,mean=None);allmissing=summary_present([None,None]);assert allmissing==dict(n_total=2,n_valid=0,mean=None);withzero=summary_present([0.0,None]);assert withzero==dict(n_total=2,n_valid=1,mean=0.0);runtime['guardedEmpty']=empty;runtime['allMissing']=allmissing;runtime['validZeroPreserved']=withzero;add('function_empty_valid_count',empty['n_valid']);add('function_allmissing_valid_count',allmissing['n_valid']);add('function_valid_zero_count',withzero['n_valid'])
first=[float(o['value']) for o in records['country'][:3]];repeated=first*2;doubled=[x*2 for x in first];assert len(repeated)==6 and len(doubled)==3 and repeated==first+first and all(y==2*x for x,y in zip(first,doubled));near(sum(repeated),sum(doubled));path=DATA/'first3-GDP-container-versus-elementwise-operation-contract.csv';S=read(path);note(path,'native Python list repetition checked against distinct explicit elementwise transformation')
for name,output in [('original_first3_values',first),('Python_numeric_list_times2',repeated),('Python_list_comprehension_value_times2',doubled),('R_numeric_vector_times2',doubled)]:
 r=next(r for r in S if r['operation']==name);same(Q(len(first)),r['source_values']);same(Q(len(output)),r['output_values']);add(name+'_output_length',len(output));add(name+'_output_sum',sum(output));add(name+'_first_value',output[0])
path=DATA/'source-aware-language-type-contracts.csv';T=read(path);note(path,'documented contracts distinguished from actual native runtime types');assert len(T)==9
path=DATA/'actual-nonunique407-code-two-distinct-source-rows.csv';S=read(path);note(path,'both original407 rows kept; source-key lookup is separate from positional indexing');dup=[o for o in records['company'] if o['code']=='407'];assert [o['sourceRow'] for o in dup]==[42,168]
for o,r in zip(dup,S):same(Q(o['sourceRow']),r['sourceRow']);same(o['value'],r['valueExactFraction']);add('code407_sourceRow'+str(o['sourceRow'])+'_before',o['before']);add('code407_sourceRow'+str(o['sourceRow'])+'_after',o['after']);add('code407_sourceRow'+str(o['sourceRow'])+'_change',o['value'])
add('stores_distinct_original_code_count',len(set(o['code'] for o in records['company'])));add('stores_unique_source_key_count',len(set(o['sourceRow'] for o in records['company'])));add('country_first_source_position',records['country'][0]['sourceRow']);CHECKS['actualNativeFunctionInputsAndEmptyMissingZeroCasesExecuted']=True;CHECKS['noRuntimeCatalogOrCaseJSONUsedAsNumericInput']=True
RUNTIME_AUDIT={'pythonVersion':platform.python_version(),'pythonExecutable':sys.executable,'actualNativeFunctionResults':runtime,'operatorScope':'Native Python list/elementwise loops; base R independently runs rep and numeric-vector arithmetic. A label for R semantics in this file is not claimed as Python executing R.','RruntimeVersionFile':'data02-r-runtime.txt'}

rpath=ROOT/'data02-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/'data02-results.json').write_text(json.dumps(dict(chapter='DATA-02',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,runtimeAudit=RUNTIME_AUDIT,interpretation='Original archived public observations are numeric inputs. Source keys and original codes are labels distinct from quantities. Explicit missing-token mapping preserves3613/3010/603 person rows and410/384/26 paired store rows;407 retains two distinct original records. Native list repetition is distinct from elementwise arithmetic even when sums match. Short summary functions receive explicit inputs and guard empty/all-missing data while preserving valid zeros. Actual runtime metadata is separate from numeric metrics; browser recorded execution catalog is authored separately.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('DATA-02:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
