"""DATA-07: 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/'data07-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

def avg(v):return sum(v,Q(0))/len(v)
def verify(name,expected):
 path=DATA/name;S=read(path);note(path,'all actual cells/derived summaries independently reconstructed; not a source of precomputed metrics');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
position={(r['countryiso3code'],r['date'],r['indicator']['id']):i for i,r in enumerate(original,1)} if originalfile.is_file() else {}
countries=sorted(countries,key=lambda r:(Q(r['gdp_pc']),r['country']));population=sum((Q(r['population']) for r in countries),Q(0));mu=avg([Q(r['gdp_pc']) for r in countries]);weighted=sum((Q(r['gdp_pc'])*Q(r['population']) for r in countries),Q(0))/population
country=[]
for r in countries:
 if position:same(Q(lookup[(r['country'],'2024','SP.POP.TOTL')]),r['population'])
 country.append(dict(country_ISO=r['country'],country_name=r['country_name'],year=2024,GDP_source_API_row=position.get((r['country'],'2024','NY.GDP.PCAP.KD')),population_source_API_row=position.get((r['country'],'2024','SP.POP.TOTL')),actual_GDPpc_constant2015USD_source_decimal=r['gdp_pc'],actual_population_source_decimal=r['population'],country_equal_weight_exact=Q(1,16),population_weight_exact=Q(r['population'])/population,equal_weight_GDP_contribution_exact=Q(r['gdp_pc'])/16,population_weight_GDP_contribution_exact=Q(r['gdp_pc'])*Q(r['population'])/population))
if not position:
 S=read(DATA/'actual16-country-indicators-and-explicit-target-weights.csv')
 for o,r in zip(country,S):o['GDP_source_API_row']=int(r['GDP_source_API_row']);o['population_source_API_row']=int(r['population_source_API_row'])
verify('actual16-country-indicators-and-explicit-target-weights.csv',country)
for r in country:
 for k in ['actual_GDPpc_constant2015USD_source_decimal','actual_population_source_decimal','country_equal_weight_exact','population_weight_exact','equal_weight_GDP_contribution_exact','population_weight_GDP_contribution_exact']:add('country_'+r['country_ISO']+'_'+k,Q(r[k]))
for k,v in dict(countries=16,total_population=population,equal_country_mean=mu,population_weighted_mean=weighted,equal_weights_sum=sum((r['country_equal_weight_exact'] for r in country),Q(0)),population_weights_sum=sum((r['population_weight_exact'] for r in country),Q(0))).items():add('country_'+k,v)
verify('two-explicit-selected-country-target-summaries.csv',[dict(target='equal_selected_country_weight',units='constant2015USD_per_person_indicator',countries=16,total_selected_population_exact=population,weighted_mean_GDPpc_exact=mu),dict(target='selected_population_weight',units='constant2015USD_per_person_indicator',countries=16,total_selected_population_exact=population,weighted_mean_GDPpc_exact=weighted)])
archive=raw/'proximity.zip';source_mode='original fixed-width wage76 and trimmed log'
if archive.is_file():
 with zipfile.ZipFile(archive) as z:source_lines=z.read('nls.dat').decode('ascii').splitlines();book=z.read('code_bk.txt').decode('ascii')
 assert 'cents per hour' in book;raw_wages=[field(line,128,132) for line in source_lines]
else:
 source_mode='retained actual source wage observation CSV; original archive unavailable';raw_wages=[Q(r['raw_hourly_wage1976_cents_source_decimal']) if r['raw_hourly_wage1976_cents_source_decimal'] else None for r in read(DATA/'actual3613-raw-wage-and-source-trimmed-log-missing-preserved.csv')]
persons=[]
for i,(rawv,o,r) in enumerate(zip(raw_wages,people,C),1):persons.append(dict(source_row_id=i,source_person_code=str(int(o['person'])),raw_hourly_wage1976_cents_source_decimal=rawv,raw_hourly_wage1976_USD_exact=None if rawv is None else rawv/100,source_trimmed_log1976_cents_source_decimal=r['log_wage'],raw_value_available=rawv is not None,source_trimmed_log_available=o['log_wage'] is not None))
verify('actual3613-raw-wage-and-source-trimmed-log-missing-preserved.csv',persons);wages=[v/100 for v in raw_wages if v is not None];bounds=list(map(Q,[0,2,4,8,16,25]));bins=[]
for a,c in zip(bounds,bounds[1:]):
 n=sum(a<=v<c or (c==bounds[-1] and v==c) for v in wages);width=c-a;bins.append(dict(lower1976USD_per_hour_exact=a,upper1976USD_per_hour_exact=c,left_closed=True,right_closed=c==bounds[-1],width1976USD_per_hour_exact=width,actual_valid_frequency=n,valid_denominator=len(wages),relative_frequency_exact=Q(n,len(wages)),density_per_1976USD_per_hour_exact=Q(n,len(wages))/width,bar_area_exact=Q(n,len(wages))))
verify('actual-raw-wage-unequal-width-histogram-counts-and-densities.csv',bins)
for i,row in enumerate(bins):
 for k in ['lower1976USD_per_hour_exact','upper1976USD_per_hour_exact','width1976USD_per_hour_exact','actual_valid_frequency','valid_denominator','relative_frequency_exact','density_per_1976USD_per_hour_exact','bar_area_exact']:add('person_bin'+str(i)+'_'+k,row[k])
summary=dict(source_rows=len(people),raw_wages_available=len(wages),raw_wages_unavailable=sum(v is None for v in raw_wages),source_trimmed_logs_available=len(w),source_trimmed_logs_unavailable=len(people)-len(w),raw_available_log_unavailable=sum(v is not None and o['log_wage'] is None for v,o in zip(raw_wages,people)),raw_wage_min1976USD_exact=min(wages),raw_wage_max1976USD_exact=max(wages),raw_wage_mean1976USD_exact=avg(wages),raw_wage_median1976USD_exact=sorted(wages)[len(wages)//2]);verify('actual-raw-wage-availability-and-centers.csv',[summary])
for k,v in summary.items():add('person_'+k,v)
assert sum(r['actual_valid_frequency'] for r in bins)==len(wages) and sum((r['density_per_1976USD_per_hour_exact']*r['width1976USD_per_hour_exact'] for r in bins),Q(0))==1;add('person_density_total_area',Q(1))
CH=read(COMMON/'churn.csv');note(COMMON/'churn.csv','actual retained3150 customer rows');archive=raw/'churn.zip'
if archive.is_file():
 note(archive,'original UCI3150x14 customer observations',True)
 with zipfile.ZipFile(archive) as z:original_churn=list(csv.DictReader(io.StringIO(z.read('Customer Churn.csv').decode('utf-8-sig'))))
 for i,(r,o) in enumerate(zip(CH,original_churn),1):
  same(Q(i),r['row_id'])
  for k,v in o.items():same(Q(v),r[k.strip().lower().replace(' ','_')])
 assert len(original_churn)==len(CH)==3150
customers=[dict(source_row_id=i,complaint_code_source_decimal=r['complains'],churn_code_source_decimal=r['churn']) for i,r in enumerate(CH,1)];verify('actual3150-customer-complaint-and-churn-source-codes.csv',customers)
cells=[]
for a in [0,1]:
 group=[r for r in customers if Q(r['complaint_code_source_decimal'])==a]
 for c in [0,1]:
  n=sum(Q(r['churn_code_source_decimal'])==c for r in group);d=sum(Q(r['churn_code_source_decimal'])==c for r in customers);cells.append(dict(complaint_code=a,churn_code=c,count=n,all_customer_denominator=len(customers),complaint_group_denominator=len(group),churn_group_denominator=d,joint_share_exact=Q(n,len(customers)),within_complaint_share_exact=Q(n,len(group)),within_churn_share_exact=Q(n,d)))
verify('actual-customer-four-cells-with-three-explicit-denominators.csv',cells)
for r in cells:
 for k,v in r.items():
  if k not in ['complaint_code','churn_code']:add('company_cell'+str(r['complaint_code'])+str(r['churn_code'])+'_'+k,v)
groups=[]
for a in [0,1]:
 r=next(r for r in cells if r['complaint_code']==a and r['churn_code']==1);groups.append(dict(complaint_code=a,all_group_records=r['complaint_group_denominator'],churn_records=r['count'],nonchurn_records=r['complaint_group_denominator']-r['count'],churn_within_complaint_exact=r['within_complaint_share_exact'],share_among_all_churn_exact=r['within_churn_share_exact']))
verify('actual-two-complaint-group-counts-and-rates.csv',groups)
for r in groups:
 for k,v in r.items():
  if k!='complaint_code':add('company_group'+str(r['complaint_code'])+'_'+k,v)
CHECKS.update(originalObservationsReconstructed=True,unknownWagesZeroFilled=False,unequalBinsAreaOne=True,sourceModeRawWage=source_mode,equalCountryVersusPopulationTargetsExplicit=True,threeCustomerDenominatorsSeparate=True)

rpath=ROOT/'data07-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/'data07-results.json').write_text(json.dumps(dict(chapter='DATA-07',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,interpretation='Actual original observations supply numeric inputs. Exact country versus population weights, raw1976 wage3017 versus trimmedlog3010 and unequal histogram density area, and customer joint/within-complaint/within-churn denominators are independently reconstructed. No case JSON or previous metric supplies input numbers. No imputed missing wages, invented sampling independence, individual-income distribution, company identity, observation calendar year or intervention effect.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('DATA-07:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
