"""DATA-06: 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/'data06-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




import sqlite3,platform

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,'all retained cells and key/NULL combinations independently rebuilt from original observations');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 isinstance(v,bool):assert row[k]==str(v),(name,k,row[k],v)
   elif v is None:assert row[k]=='',(name,k,row[k])
   elif isinstance(v,(Q,int)):same(Q(v),row[k])
   else:assert row[k]==str(v),(name,k,row[k],v)
 return S
positions={(r['countryiso3code'],r['date'],r['indicator']['id']):i for i,r in enumerate(original,1)} if originalfile.is_file() else {}
gdp=[dict(source_API_row=positions.get((r['country'],r['year'],'NY.GDP.PCAP.KD')),country_ISO=r['country'],year=r['year'],value_source_decimal=r['gdp_pc'],indicator='NY.GDP.PCAP.KD') for r in W];life=[dict(source_API_row=positions.get((r['country'],r['year'],'SP.DYN.LE00.IN')),country_ISO=r['country'],year=r['year'],value_source_decimal=r['life_expectancy'],indicator='SP.DYN.LE00.IN') for r in W]
if positions:verify('actual720-GDP-table-with-composite-keys.csv',gdp);verify('actual720-life-table-with-composite-keys.csv',life)
else:
 for name,rows in [('actual720-GDP-table-with-composite-keys.csv',gdp),('actual720-life-table-with-composite-keys.csv',life)]:
  S=read(DATA/name)
  for o,r in zip(rows,S):o['source_API_row']=int(r['source_API_row'])
  verify(name,rows)
assert len(set((r['country_ISO'],r['year']) for r in gdp))==720;bycountry=Counter(r['country_ISO'] for r in gdp);wrongcountry=sum(n*n for n in bycountry.values());assert wrongcountry==32400
joined=[dict(country_ISO=a['country_ISO'],GDP_year=a['year'],life_year=c['year'],actual_GDPpc_source_decimal=a['value_source_decimal'],actual_period_life_years_source_decimal=c['value_source_decimal'],GDP_source_API_row=a['source_API_row'],life_source_API_row=c['source_API_row']) for a,c in zip(gdp,life)];verify('actual720-correct-same-year-keyed-join.csv',joined)
wrongexamples=[dict(country_ISO=a['country_ISO'],GDP_year=a['year'],life_year=c['year'],GDP_source_decimal=a['value_source_decimal'],life_source_decimal=c['value_source_decimal'],is_actual_same_year_record=False) for a in gdp[:2] for c in life if c['country_ISO']==a['country_ISO'] and c['year']!=a['year']][:8];verify('eight-explicit-invalid-crossyear-combination-examples.csv',wrongexamples)
verify('country-correct-versus-invalid-join-cardinality.csv',[dict(join_rule='ISO_and_same_year',left_rows=720,right_rows=720,result_rows=720,observed_same_year_key_matches=True),dict(join_rule='deliberately_invalid_ISO_only',left_rows=720,right_rows=720,result_rows=wrongcountry,observed_same_year_key_matches=False)])
for k,v in dict(GDP_rows=len(gdp),life_rows=len(life),correct_keyed_rows=len(joined),invalid_country_only_combinations=wrongcountry,countries=len(bycountry),GDP_nulls=sum(r['value_source_decimal']=='' for r in gdp)).items():add('country_'+k,v)
demo=[dict(source_row_id=i,source_person_code=str(int(o['person'])),education_years=C[i-1]['education'],school_group='schooling_le12' if o['education']<=12 else 'schooling_gt12') for i,o in enumerate(people,1)];full=[dict(source_row_id=i,log_wage_source_decimal=C[i-1]['log_wage']) for i in range(1,len(people)+1)];available=[r for r in full if r['log_wage_source_decimal']!=''];verify('actual3613-person-demographics-keyed.csv',demo);verify('actual3613-outcome-keys-including603-NULL-values.csv',full);verify('actual3010-available-only-outcome-keys.csv',available)
groups=[]
for group in ['schooling_le12','schooling_gt12']:
 ids=[r['source_row_id'] for r in demo if r['school_group']==group];values=[people[i-1]['log_wage'] for i in ids if people[i-1]['log_wage'] is not None];row=dict(school_group=group,COUNT_all_source_rows=len(ids),COUNT_nonNULL_log=len(values),source_unavailable_logs=len(ids)-len(values),available_log_SUM_exact=sum(values,Q(0)),available_log_AVG_exact=avg(values),invalid_AVG_COALESCE_zero_exact=sum(values,Q(0))/len(ids));groups.append(row)
 for k,v in row.items():
  if k!='school_group':add('person_'+group+'_'+k,v)
verify('actual-two-education-groups-NULL-aware-aggregates.csv',groups)
variants=[dict(right_table='full3613_including603_NULL_logs',join_rule='INNER_on_source_row_id',left_source_rows=3613,right_rows=3613,result_rows=3613,unmatched_left_keys=0,matched_NULL_log_rows=603,available_log_values=3010),dict(right_table='available_only3010_log_rows',join_rule='INNER_on_source_row_id',left_source_rows=3613,right_rows=3010,result_rows=3010,unmatched_left_keys=603,matched_NULL_log_rows=0,available_log_values=3010),dict(right_table='available_only3010_log_rows',join_rule='LEFT_on_source_row_id',left_source_rows=3613,right_rows=3010,result_rows=3613,unmatched_left_keys=603,matched_NULL_log_rows=0,available_log_values=3010),dict(right_table='available_only3010_log_rows',join_rule='LEFT_then_WHERE_log_IS_NOT_NULL',left_source_rows=3613,right_rows=3010,result_rows=3010,unmatched_left_keys=603,matched_NULL_log_rows=0,available_log_values=3010)]
verify('explicit-right-table-designs-and-join-result-counts.csv',variants)
for i,r in enumerate(variants):
 for key in ['right_rows','result_rows','unmatched_left_keys','matched_NULL_log_rows','available_log_values']:add('person_variant'+str(i)+'_'+key,r[key])
before=[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_source_decimal=NJ[i-1]['fte_before']) for i,o in enumerate(stores,1)];after=[dict(source_row_id=i,original_store_code=str(int(o['store'])),after_FTE_source_decimal=NJ[i-1]['fte_after']) for i,o in enumerate(stores,1)];verify('actual410-before-wave-keyed-source-records.csv',before);verify('actual410-after-wave-keyed-source-records.csv',after)
def pair(a,c,rule):
 bv=stores[a['source_row_id']-1]['fte_before'];av=stores[c['source_row_id']-1]['fte_after'];return dict(before_source_row_id=a['source_row_id'],after_source_row_id=c['source_row_id'],original_store_code=a['original_store_code'],before_FTE_source_decimal=a['before_FTE_source_decimal'],after_FTE_source_decimal=c['after_FTE_source_decimal'],change_FTE_exact=av-bv if av is not None and bv is not None else None,same_original_source_record=a['source_row_id']==c['source_row_id'],join_rule=rule)
correct=[pair(a,c,'correct_source_row_key') for a,c in zip(before,after)];wrong=[pair(a,c,'deliberately_invalid_original_code_only') for a in before for c in after if a['original_store_code']==c['original_store_code']];verify('actual410-valid-source-row-joined-records.csv',correct);verify('explicit412-invalid-code-only-combinations.csv',wrong);verify('actual-code407-cross-combinations-not-all-valid-pairs.csv',[r for r in wrong if r['original_store_code']=='407'])
summaries=[]
for name,rows in [('correct_source_row_key',correct),('deliberately_invalid_original_code_only',wrong)]:
 values=[r['change_FTE_exact'] for r in rows if r['change_FTE_exact'] is not None];row=dict(join_rule=name,result_rows=len(rows),complete_value_combinations=len(values),unavailable_difference_rows=len(rows)-len(values),mean_difference_FTE_exact=avg(values),crossed_source_row_combinations=sum(not r['same_original_source_record'] for r in rows));summaries.append(row)
 for k,v in row.items():
  if k!='join_rule':add('company_'+name+'_'+k,v)
verify('correct-and-invalid-store-join-counts-and-means.csv',summaries)
# Recreate a new actual SQLite database from independent raw-source records.
db=sqlite3.connect(':memory:');db.executescript('CREATE TABLE gdp(iso TEXT,year TEXT,gdp REAL,PRIMARY KEY(iso,year));CREATE TABLE life(iso TEXT,year TEXT,life REAL,PRIMARY KEY(iso,year));CREATE TABLE people(source_row_id INTEGER PRIMARY KEY,school_group TEXT);CREATE TABLE outcome_full(source_row_id INTEGER PRIMARY KEY,log_wage REAL);CREATE TABLE outcome_available(source_row_id INTEGER PRIMARY KEY,log_wage REAL);CREATE TABLE before_wave(source_row_id INTEGER PRIMARY KEY,store_code TEXT,before_FTE REAL);CREATE TABLE after_wave(source_row_id INTEGER PRIMARY KEY,store_code TEXT,after_FTE REAL);')
numeric=lambda x:float(Q(x)) if x!='' else None
db.executemany('INSERT INTO gdp VALUES(?,?,?)',[(r['country_ISO'],r['year'],numeric(r['value_source_decimal'])) for r in gdp]);db.executemany('INSERT INTO life VALUES(?,?,?)',[(r['country_ISO'],r['year'],numeric(r['value_source_decimal'])) for r in life]);db.executemany('INSERT INTO people VALUES(?,?)',[(r['source_row_id'],r['school_group']) for r in demo]);db.executemany('INSERT INTO outcome_full VALUES(?,?)',[(r['source_row_id'],numeric(r['log_wage_source_decimal'])) for r in full]);db.executemany('INSERT INTO outcome_available VALUES(?,?)',[(r['source_row_id'],numeric(r['log_wage_source_decimal'])) for r in available]);db.executemany('INSERT INTO before_wave VALUES(?,?,?)',[(r['source_row_id'],r['original_store_code'],numeric(r['before_FTE_source_decimal'])) for r in before]);db.executemany('INSERT INTO after_wave VALUES(?,?,?)',[(r['source_row_id'],r['original_store_code'],numeric(r['after_FTE_source_decimal'])) for r in after])
queries={'country_correct':'SELECT COUNT(*) FROM gdp g JOIN life l ON g.iso=l.iso AND g.year=l.year;','country_wrong':'SELECT COUNT(*) FROM gdp g JOIN life l ON g.iso=l.iso;','person_full_inner':'SELECT COUNT(*),COUNT(w.log_wage) FROM people p INNER JOIN outcome_full w ON p.source_row_id=w.source_row_id;','person_available_inner':'SELECT COUNT(*),COUNT(w.log_wage) FROM people p INNER JOIN outcome_available w ON p.source_row_id=w.source_row_id;','person_available_left':'SELECT COUNT(*),COUNT(w.log_wage) FROM people p LEFT JOIN outcome_available w ON p.source_row_id=w.source_row_id;','person_left_then_where':'SELECT COUNT(*),COUNT(w.log_wage) FROM people p LEFT JOIN outcome_available w ON p.source_row_id=w.source_row_id WHERE w.log_wage IS NOT NULL;','person_groups':'SELECT p.school_group,COUNT(*),COUNT(w.log_wage),AVG(w.log_wage),AVG(COALESCE(w.log_wage,0)) FROM people p LEFT JOIN outcome_full w ON p.source_row_id=w.source_row_id GROUP BY p.school_group ORDER BY p.school_group;','company_correct':'SELECT COUNT(*),COUNT(a.after_FTE-b.before_FTE),AVG(a.after_FTE-b.before_FTE) FROM before_wave b JOIN after_wave a ON b.source_row_id=a.source_row_id;','company_wrong':'SELECT COUNT(*),COUNT(a.after_FTE-b.before_FTE),AVG(a.after_FTE-b.before_FTE) FROM before_wave b JOIN after_wave a ON b.store_code=a.store_code;','company407_wrong_pairs':"SELECT b.source_row_id,a.source_row_id,a.after_FTE-b.before_FTE FROM before_wave b JOIN after_wave a ON b.store_code=a.store_code WHERE b.store_code='407' ORDER BY b.source_row_id,a.source_row_id;"}
executed={key:[list(r) for r in db.execute(sql).fetchall()] for key,sql in queries.items()};db.close();path=DATA/'actual-native-SQLite-execution.json';note(path,'stored native-query audit checked against newly executed independent SQLite, not used as calculation input');audit=json.loads(path.read_text(encoding='utf-8'))
for key,rows in executed.items():
 expected=audit['queries'][key]['rows'];assert len(rows)==len(expected)
 for a,c in zip(rows,expected):
  for v,z in zip(a,c):
   if isinstance(v,(int,float)):near(v,z)
   else:assert v==z
assert executed['country_correct']==[[720]] and executed['country_wrong']==[[32400]]
for i,key in enumerate(['person_full_inner','person_available_inner','person_available_left','person_left_then_where']):assert executed[key]==[[variants[i]['result_rows'],3010]]
for r in executed['person_groups']:
 expected=next(g for g in groups if g['school_group']==r[0]);assert r[1:3]==[expected['COUNT_all_source_rows'],expected['COUNT_nonNULL_log']];near(r[3],expected['available_log_AVG_exact']);near(r[4],expected['invalid_AVG_COALESCE_zero_exact'])
for key,row in zip(['company_correct','company_wrong'],summaries):actual=executed[key][0];assert actual[:2]==[row['result_rows'],row['complete_value_combinations']];near(actual[2],row['mean_difference_FTE_exact'])
for key in ['actual-source-queries-executed-in-memory.sql']:note(DATA/key,'published query text, not prior numeric source')
RUNTIME_AUDIT={'nativeLanguage':'python','actualPythonVersion':platform.python_version(),'actualSQLiteVersion':sqlite3.sqlite_version,'actualInMemoryQueriesExecuted':len(executed),'RMethod':'Base R independently reconstructs keys, joins, NULL-aware counts and exact-source summaries; no R SQL execution claimed.'}
CHECKS.update(caseJSONNotUsedAsNumericInput=True,matchedNULLDoesNotVanishInInnerJoin=True,rightOutcomeTableDesignsExplicit=True,originalCode407BothRecordsRetained=True,invalidCombinationsNotActualMeasurements=True,externalDatabaseMutated=False)

rpath=ROOT/'data06-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/'data06-results.json').write_text(json.dumps(dict(chapter='DATA-06',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,runtimeAudit=RUNTIME_AUDIT,interpretation='Independent original/retained public source observations feed new SQL tables and exact Fraction aggregates; prior case/results JSON is not numeric input. Composite keys preserve720 same-year rows; country-only32400 combinations are invalid same-year linkage. A matched NULL differs from an absent right key, and full3613 versus available-only3010 outcome tables differ by design. Preserve both407 source records; crossed code-only combinations are not actual changes. R uses independent base joins/aggregation, not an uninstalled SQL package. No causal or independence claim follows from linkage.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('DATA-06:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
