"""DATA-03: 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/'data03-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 subprocess,sys,os,platform
def avg(v):return sum(v,Q(0))/len(v)
def samplevar(v):u=avg(v);return sum(((x-u)**2 for x in v),Q(0))/(len(v)-1)
source_positions={(r['countryiso3code'],r['date'],r['indicator']['id']):i for i,r in enumerate(original,1)} if originalfile.is_file() else {}
country=[dict(sourceRow=source_positions.get((o['country'],'2024','NY.GDP.PCAP.KD')),countryISO=o['country'],year='2024',indicator='NY.GDP.PCAP.KD',GDPpc_source_decimal=o['gdp_pc'],unit='constant2015USD/person') for o in countries]
def canonical(rows,keys,fields):
 normalized=[]
 for r in sorted(rows,key=lambda r:tuple(str(r[k]) for k in keys)):
  normalized.append({k:str(Q(r[k])) if k in ['GDPpc_source_decimal','before_FTE','after_FTE','change_FTE'] and r[k]!='' else str(r[k]) for k in fields})
 return hashlib.sha256(json.dumps(normalized,ensure_ascii=False,sort_keys=True,separators=(',',':')).encode('utf-8')).hexdigest()
canonical_country=canonical(country,['countryISO','year','indicator'],list(country[0]));identity=[]
for label in ['LF','CRLF']:
 path=DATA/('working-country-same-cells-'+label+'.csv');S=read(path);note(path,'actual source records, line-ending byte differences and specified canonical equality');assert len(S)==16
 for o,r in zip(country,S):
  for k in ['countryISO','year','indicator','unit']:assert str(o[k])==r[k]
  if o['sourceRow'] is not None:same(Q(o['sourceRow']),r['sourceRow'])
  same(Q(o['GDPpc_source_decimal']),r['GDPpc_source_decimal'])
 checksum=canonical(S,['countryISO','year','indicator'],list(S[0]));assert checksum==canonical_country;rawbytes=path.read_bytes();identity.append((label,len(rawbytes),hashlib.sha256(rawbytes).hexdigest(),checksum));add('country_'+label+'_bytes',len(rawbytes));add('country_'+label+'_parsed_records',len(S));add('country_'+label+'_mean',avg([Q(o['GDPpc_source_decimal']) for o in country]))
assert identity[0][2]!=identity[1][2] and identity[0][3]==identity[1][3];path=DATA/'country-byte-versus-specified-canonical-identities.csv';S=read(path);note(path,'byte and canonical identities independently calculated')
for (label,size,bytehash,keyhash),r in zip(identity,S):same(Q(size),r['actual_bytes']);assert r['actual_byte_SHA256']==bytehash and r['specified_key_value_canonical_SHA256']==keyhash
path=DATA/'actual3613-person-source-logs-missing-preserved.csv';S=read(path);note(path,'actual copied person records and603 unavailable logs checked against fixed-width source')
for i,(o,r) in enumerate(zip(people,S),1):
 same(Q(i),r['sourceRow']);same(o['person'],r['source_person_code'])
 if o['log_wage'] is None:assert r['actual_source_trimmed1976_log_hourly_wage_cents']==''
 else:same(o['log_wage'],r['actual_source_trimmed1976_log_hourly_wage_cents'])
probe=DATA/'fresh-process-person-summary.py';note(probe,'actual native-language probe code executed below in fresh processes');notebookpath=DATA/'unexecuted-person-summary-source-example.ipynb';note(notebookpath,'unexecuted notebook source, no kernel-run claim');nb=json.loads(notebookpath.read_text(encoding='utf-8'));assert nb['nbformat']==4;cells=[c for c in nb['cells'] if c['cell_type']=='code'];assert all(c['execution_count'] is None and c['outputs']==[] for c in cells);compile(''.join(''.join(c['source']) for c in cells),'unexecuted_notebook_source','exec');add('notebook_code_cells',len(cells));add('notebook_stored_outputs',sum(len(c['outputs']) for c in cells));add('notebook_recorded_executions',sum(c['execution_count'] is not None for c in cells))
native_runs=[];env=os.environ.copy();env['PYTHONIOENCODING']='utf-8'
for i,cwd in enumerate([WORKSPACE,WORKSPACE/'work/tmp']):
 proc=subprocess.run([sys.executable,str(probe.resolve())],cwd=cwd,env=env,capture_output=True,text=True,encoding='utf-8',timeout=30);assert proc.returncode==0;result=json.loads(proc.stdout);assert (result['nTotal'],result['nValid'],result['nMissing'])==(3613,3010,603);same(avg(w),result['meanExact']);near(result['mean'],avg(w));native_runs.append(dict(language='python',cwdLabel=['workspace','different_subfolder'][i],returnCode=proc.returncode,stdout=proc.stdout,stderr=proc.stderr,codeSha256=hashlib.sha256(probe.read_bytes()).hexdigest(),actualNativeExecution=True))
 for k in ['nTotal','nValid','nMissing','mean']:add('native_probe_launch'+str(i)+'_'+k,result[k])
store_rows=[]
for i,o in enumerate(stores,1):store_rows.append(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'])),before_FTE=str(o['fte_before']) if o['fte_before'] is not None else '',after_FTE=str(o['fte_after']) if o['fte_after'] is not None else '',change_FTE=str(o['fte_after']-o['fte_before']) if o['fte_after'] is not None and o['fte_before'] is not None else ''))
fields=list(store_rows[0]);storecanonical=canonical(store_rows,['source_row_id'],fields);fileids=[]
for label,name in [('original','working-stores-original-order.csv'),('sorted','working-stores-sorted-whole-rows.csv')]:
 path=DATA/name;S=read(path);note(path,'original and whole-row sorted copies preserve original keys and both waves');expected=store_rows if label=='original' else sorted(store_rows,key=lambda r:(int(r['original_store_code']),r['source_row_id']));assert len(S)==len(expected)==410
 for o,r in zip(expected,S):
  same(Q(o['source_row_id']),r['source_row_id']);assert o['original_store_code']==r['original_store_code'] and o['state']==r['state'] and o['chain_code']==r['chain_code']
  for key in ['before_FTE','after_FTE','change_FTE']:
   if o[key]=='':assert r[key]==''
   else:same(Q(o[key]),r[key])
 checksum=canonical(S,['source_row_id'],fields);assert checksum==storecanonical;fileids.append((path.name,path.stat().st_size,hashlib.sha256(path.read_bytes()).hexdigest(),checksum));add('company_'+label+'_bytes',path.stat().st_size);add('company_'+label+'_rows',len(S));add('company_'+label+'_complete_pairs',sum(r['change_FTE']!='' for r in S));add('company_'+label+'_distinct_codes',len(set(r['original_store_code'] for r in S)))
path=DATA/'store-order-versus-preserved-key-identities.csv';S=read(path);note(path,'actual byte identities and specified order-invariant key checks')
for (name,size,hashvalue,keyhash),r in zip(fileids,S):same(Q(size),r['actual_bytes']);assert r['actual_byte_SHA256']==hashvalue and r['specified_key_value_canonical_SHA256']==keyhash
paired=[r for r in store_rows if r['change_FTE']!=''];before=[Q(r['before_FTE']) for r in paired];after=[Q(r['after_FTE']) for r in paired];correct=[a-b for a,b in zip(after,before)];after_permuted=[Q(r['after_FTE']) for r in sorted(paired,key=lambda r:(int(r['original_store_code']),r['source_row_id']))];invalid=[a-b for a,b in zip(after_permuted,before)];assert avg(correct)==avg(invalid);changed=sum(a!=b for a,b in zip(correct,invalid));path=DATA/'valid-pairing-versus-deliberately-invalid-position-match.csv';S=read(path);note(path,'explicit invalid after-only permutation, not actual observations')
for name,values,r in zip(['correct','invalid_demonstration'],[correct,invalid],S):
 vals=dict(original_complete_pairs=Q(len(values)),mean_change_FTE_exact=avg(values),sample_variance_of_change_FTE2_exact=samplevar(values),mean_absolute_change_FTE_exact=avg([abs(x) for x in values]),different_values_from_correct_pairing=Q(0 if name=='correct' else changed))
 for key,value in vals.items():same(value,r[key]);add('company_'+name+'_'+key,value)
manifestpath=DATA/'actual-path-replays-and-artifact-manifest.json';note(manifestpath,'actual generator replay audit, used to verify artifact hashes not as numeric source');manifest=json.loads(manifestpath.read_text(encoding='utf-8'));assert len(manifest['freshProcessReplays'])==4 and all(not r['executed_by_Jupyter_kernel'] for r in manifest['freshProcessReplays'])
for artifact in manifest['artifacts']:assert hashlib.sha256((ROOT/artifact['file']).read_bytes()).hexdigest()==artifact['sha256']
CHECKS['freshNativeProcessesExecuted']=2;CHECKS['actualNotebookKernelExecutionClaimed']=False;CHECKS['originalSourceAndBoth407RowsPreserved']=True;CHECKS['caseJSONNotUsedAsNumericInput']=True
RUNTIME_AUDIT={'nativeLanguage':'python','version':platform.python_version(),'freshProcesses':native_runs,'notebookStatus':'Unexecuted source example, JSON/compile check only; no Jupyter-kernel execution.'}

rpath=ROOT/'data03-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/'data03-results.json').write_text(json.dumps(dict(chapter='DATA-03',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,runtimeAudit=RUNTIME_AUDIT,interpretation='Actual archived data are independent numeric inputs. Original archives remain unchanged. LF/CRLF bytes differ while parsed records and explicitly scoped canonical checks agree. Source-anchored probes run in fresh native processes from two working directories; an unexecuted notebook is not claimed as a kernel run. Whole-row sorting preserves source-key pairs, while a deliberately invalid after-only permutation can preserve the mean yet change pairs and variance. Hashes and reproducibility do not establish source authority, model truth or independent empirical replication.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('DATA-03:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
