"""DATA-05: 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/'data05-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)
sourcepositions={(r['countryiso3code'],r['date'],r['indicator']['id']):i for i,r in enumerate(original,1)} if originalfile.is_file() else {}
path=DATA/'actual720-country-year-GDP-and-source-nulls.csv';S=read(path);note(path,'all actual source GDP nulls/values and API positions independently compared');assert len(S)==len(W)==720
for o,r in zip(W,S):
 assert r['country_ISO']==o['country'] and r['year']==o['year'] and r['missing_replacement_applied']=='False'
 if sourcepositions:same(Q(sourcepositions[(o['country'],o['year'],'NY.GDP.PCAP.KD')]),r['source_API_row'])
 if o['gdp_pc']=='':assert r['actual_source_GDPpc_decimal']=='' and r['source_value_available']=='False'
 else:same(Q(o['gdp_pc']),r['actual_source_GDPpc_decimal']);assert r['source_value_available']=='True'
add('country_source_rows',len(W));add('country_source_GDP_available',sum(r['gdp_pc']!='' for r in W));add('country_source_GDP_missing',sum(r['gdp_pc']=='' for r in W))
path=DATA/'actual45-year-denominators-and-invalid-zero-fill-comparison.csv';S=read(path);note(path,'all actual annual denominators and explicitly invalid zero-fill comparisons');assert len(S)==45
for year,r in zip(range(1980,2025),S):
 rows=[o for o in W if int(o['year'])==year];values=[Q(o['gdp_pc']) for o in rows if o['gdp_pc']!=''];vals=dict(planned_country_records=len(rows),available_country_values=len(values),unavailable_values=len(rows)-len(values),available_sum_exact=sum(values,Q(0)),available_country_mean_exact=avg(values),deliberately_invalid_zero_filled_mean_exact=sum(values,Q(0))/len(rows));same(Q(year),r['year']);assert r['zero_fill_is_actual_source_data']=='False'
 for key,value in vals.items():same(Q(value),r[key]);add('country_year'+str(year)+'_'+key,value)
 if year<=1983:assert vals['deliberately_invalid_zero_filled_mean_exact']==Q(15,16)*vals['available_country_mean_exact']
ordered=sorted(w)
def interp7(p):
 position=Q(len(ordered)-1)*p;j=position.numerator//position.denominator;weight=position-j;return ordered[j]+weight*(ordered[min(j+1,len(ordered)-1)]-ordered[j])
q1=interp7(Q(1,4));q3=interp7(Q(3,4));iqr=q3-q1;lo=q1-Q(3,2)*iqr;hi=q3+Q(3,2)*iqr;inside=[v for v in w if lo<=v<=hi];low=sum(v<lo for v in w);high=sum(v>hi for v in w)
path=DATA/'actual3613-person-source-values-and-chosen-review-flags.csv';S=read(path);note(path,'all original people including603 unavailable source logs and exact chosen review flags');assert len(S)==3613
for i,(o,r) in enumerate(zip(people,S),1):
 same(Q(i),r['source_row_id']);same(o['person'],r['source_person_code']);same(o['education'],r['education_source_years']);assert r['original_record_deleted']=='False';v=o['log_wage'];flag='source_log_missing' if v is None else 'below_chosen_fence' if v<lo else 'above_chosen_fence' if v>hi else 'inside_chosen_fences';assert r['chosen_type7_IQR_flag']==flag
 if v is None:assert r['actual1976_source_trimmed_log_wage_cents']==''
 else:same(v,r['actual1976_source_trimmed_log_wage_cents'])
path=DATA/'chosen-type7-IQR-fences-and-illustrative-removal-comparison.csv';S=read(path);note(path,'exact chosen type7/1.5IQR fences and descriptive change under illustrative exclusion');assert len(S)==1 and S[0]['flag_is_verified_record_error']=='False';vals=dict(available_n=len(w),Q1_exact=q1,Q3_exact=q3,IQR_exact=iqr,chosen_multiplier_exact=Q(3,2),lower_fence_exact=lo,upper_fence_exact=hi,below_count=low,above_count=high,inside_count=len(inside),available_source_mean_exact=avg(w),illustrative_flag_removed_mean_exact=avg(inside))
for key,v in vals.items():same(Q(v),S[0][key]);add('person_'+key,v)
add('person_source_records',len(people));add('person_source_unavailable_logs',len(people)-len(w))
path=COMMON/'wine.csv';retained=read(path);note(path,'actual retained red-wine numeric source copy')
archive=raw/'wine-quality.zip'
if archive.is_file():
 note(archive,'original red1599 measurements, no identified firm/item keys',True)
 with zipfile.ZipFile(archive) as z:O=list(csv.DictReader(io.StringIO(z.read('winequality-red.csv').decode('utf-8')),delimiter=';'))
 fields=list(O[0]);obs=[{k.replace(' ','_'):Q(v) for k,v in r.items()} for r in O]
else:fields=[k for k in retained[0] if k!='row_id'];obs=[{k:Q(r[k]) for k in fields} for r in retained]
assert len(obs)==len(retained)==1599
for o,r in zip(obs,retained):
 for key,value in o.items():same(value,r[key])
fieldnames=list(obs[0]);signature=[tuple(r[k] for k in fieldnames) for r in obs];positions={}
for i,key in enumerate(signature,1):positions.setdefault(key,[]).append(i)
path=DATA/'actual1599-red-wine-source-values-and-repetition-flags.csv';S=read(path);note(path,'all actual red-wine cells and full exact-numeric-signature membership, without deletion');assert len(S)==1599
for i,(o,r,key) in enumerate(zip(obs,S,signature),1):
 same(Q(i),r['source_row_id'])
 for k,value in o.items():same(value,r[k])
 same(Q(positions[key][0]),r['first_source_row_with_same12_numeric_values']);same(Q(len(positions[key])),r['same12_numeric_values_frequency']);assert r['confirmed_same_measurement_unit']=='False' and r['original_record_deleted']=='False'
path=DATA/'actual1359-numeric-value-signature-groups.csv';S=read(path);note(path,'all exact numeric groups/source-row traces checked from raw source, not duplicated flags');assert len(S)==len(positions)==1359
for (key,ids),r in zip(positions.items(),S):same(Q(ids[0]),r['signature_group_source_first_row']);same(Q(len(ids)),r['actual_matching_record_count']);same(key[-1],r['actual_quality_score_exact']);assert r['all_original_source_rows']=='|'.join(map(str,ids)) and r['confirmed_accidental_duplicate_entry']=='False'
path=DATA/'actual-signature-multiplicities-and-record-counts.csv';S=read(path);note(path,'multiplicity groups and source-record weights independently enumerated');assert len(S)==4
for m,r in zip(range(1,5),S):
 groups=sum(len(v)==m for v in positions.values());records=m*groups;same(Q(m),r['matching_values_multiplicity']);same(Q(groups),r['numeric_signature_groups']);same(Q(records),r['actual_records']);add('company_multiplicity'+str(m)+'_groups',groups);add('company_multiplicity'+str(m)+'_records',records)
allmean=avg([r['quality'] for r in obs]);onemean=avg([key[-1] for key in positions]);path=DATA/'retained-records-versus-illustrative-signature-collapse.csv';S=read(path);note(path,'explicitly different occurrence weighting, not source-verified error correction');assert len(S)==2
for name,n,mu,r in zip(['all_records','illustrative_signature_uniform'],[1599,1359],[allmean,onemean],S):same(Q(n),r['actual_record_count']);same(Q(1359),r['distinct_numeric_signatures']);same(mu,r['quality_score_mean_exact']);assert r['policy_is_source_verified_correction']=='False';add('company_'+name+'_n',n);add('company_'+name+'_numeric_quality_mean',mu)
for key,value in dict(source_records=1599,distinct_numeric_signatures=len(positions),additional_signature_occurrences=1599-len(positions),repeated_signature_groups=sum(len(v)>1 for v in positions.values()),max_signature_multiplicity=max(map(len,positions.values())),distinct_original_store_codes=len(set(r['store'] for r in stores))).items():add('company_'+key,value)
path=DATA/'actual-code407-two-distinct-source-records.csv';S=read(path);note(path,'original407 rows42/168 remain distinct actual records');collision=[(i,r) for i,r in enumerate(stores,1) if r['store']==407];assert len(collision)==len(S)==2
for (i,o),r in zip(collision,S):
 same(Q(i),r['source_row_id']);same(o['store'],r['original_store_code']);same(o['chain'],r['chain_code']);assert r['state']==('NJ' if o['nj']==1 else 'PA');assert r['duplicate_code_is_verified_duplicate_record']=='False'
 for k in ['before','after']:same(o['fte_'+k],r[k+'_FTE']);add('store_source_row'+str(i)+'_'+k+'_FTE',o['fte_'+k])
 same(o['fte_after']-o['fte_before'],r['change_FTE_exact']);add('store_source_row'+str(i)+'_change_FTE',o['fte_after']-o['fte_before'])
path=DATA/'explicit-review-rules-with-evidence-and-limits.csv';S=read(path);note(path,'source-backed review-decision contracts, not treatment instructions');assert len(S)==4
CHECKS.update(allOriginalRecordsRetained=True,missingNotZero=True,chosenFlagsNotVerifiedErrors=True,repeatedValuesNotPermanentIdentity=True,caseJSONNotUsedAsNumericInput=True)

rpath=ROOT/'data05-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/'data05-results.json').write_text(json.dumps(dict(chapter='DATA-05',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,interpretation='Original API, fixed-width and wine archive cells are numeric inputs, with retained actual-data fallbacks if unavailable. Preserve nulls and valid denominators. Chosen type7/1.5IQR flags are not verified errors; illustrative flag exclusion changes the descriptive target. Exact numeric signature repetition does not establish accidental duplicate entries or unique measurement identities. Both original code407 records remain distinct and traceable. No source rows are deleted.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('DATA-05:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
