"""STAT-10: 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
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/'stats10-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})
def add(key,value):METRICS[key]=float(value);EXACT[key]=str(Q(value))
def same(value,stored):assert value==Q(stored),(value,stored);CHECKS['selectedValuesCompared']+=1


def avg(v):return sum(v,Q(0))/len(v)
def var(v):return avg([(x-avg(v))**2 for x in v])
raw=WORKSPACE/'work'/'textbooks-2026'/'raw'
hp=COMMON/'korea-housing.csv';note(hp,'actual retained BIS real-index values');H=read(hp);assert len(H)==180
hr=raw/'korea-housing-real.csv'
if hr.is_file():
    note(hr,'actual original BIS SDMX XML',True);tree=ET.fromstring(hr.read_text(encoding='utf-8'));series=[e for e in tree.iter() if e.tag.endswith('Series')][0];assert series.attrib['REF_AREA']=='KR' and series.attrib['UNIT_MEASURE']=='628'
    original={e.attrib['TIME_PERIOD']:Q(e.attrib['OBS_VALUE']) for e in tree.iter() if e.tag.endswith('Obs')};assert len(original)==180
    for r in H:same(original[r['quarter']],r['real'])
else:original={r['quarter']:Q(r['real']) for r in H}
quarters=['2024-Q'+str(i) for i in range(1,5)];h=[original[q] for q in quarters];hmu=avg(h);hv=var(h);h4=avg([(v-hmu)**4 for v in h])
path=DATA/'actual-Korea2024-real-housing-quarter-values.csv';S=read(path);note(path,'four actual quarter values and full-law moments checked');assert len(S)==4
for q,v,r in zip(quarters,h,S):assert q==r['quarter'];same(v,r['reported_real_Korea_national_RPP_index_2010_average100']);same(hmu,r['complete_four_quarter_mean_exact']);same(hv,r['complete_four_quarter_variance_exact'])
cp=COMMON/'college-proximity.csv';note(cp,'actual retained anonymized Card records');C=read(cp);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)]
def field(line,a,b):
    v=line[a-1:b].strip();return None if v in ['','.'] else Q(v)
if archive.is_file():
    note(archive,'actual original Card codebook and nls.dat',True)
    with zipfile.ZipFile(archive) as z:lines=z.read('nls.dat').decode('ascii').splitlines();book=z.read('code_bk.txt').decode('ascii')
    assert len(lines)==len(C)==3613 and 'outliers trimmed' in book and 'cents per hour' in book
    people=[{key:field(line,a,b) for key,a,b in spec} for line in lines]
    for r,o in zip(C,people):
        for key,a,b in spec:
            if o[key] is None:assert r[key]==''
            else:same(o[key],r[key])
        assert Q(r['experience'])==o['age']-o['education']-6 and Q(r['experience_squared'])==Q(r['experience'])**2
else:people=[{key:Q(r[key]) if r[key] else None for key,a,b in spec} for r in C]
wages=[r['log_wage'] for r in people if r['log_wage'] is not None];wn=len(wages);wmu=avg(wages);wv=var(wages);assert len(C)==3613 and wn==3010
path=DATA/'actual-1976-anonymized-men-log-wages-and-missing-records.csv';S=read(path);note(path,'all actual person records and603 missing log wages retained');assert len(S)==3613
for o,r in zip(people,S):
    same(o['person'],r['source_person_ID']);same(o['education'],r['reported_education_years']);same(o['age'],r['reported_age_years'])
    if o['log_wage'] is None:assert r['reported_source_trimmed_log_wage']==r['assigned_valid_record_selection_probability_exact']==''
    else:same(o['log_wage'],r['reported_source_trimmed_log_wage']);same(Q(1,3010),r['assigned_valid_record_selection_probability_exact'])
chp=COMMON/'churn.csv';note(chp,'actual retained UCI customer records');CH=read(chp);archive=raw/'churn.zip'
if archive.is_file():
    note(archive,'actual original UCI Customer Churn.csv',True)
    with zipfile.ZipFile(archive) as z:rawrows=list(csv.DictReader(io.StringIO(z.read('Customer Churn.csv').decode('utf-8-sig'))))
    assert len(rawrows)==len(CH)==3150
    for i,(r,o) in enumerate(zip(CH,rawrows),1):
        assert int(r['row_id'])==i
        for key,v in o.items():same(Q(v),r[key.strip().lower().replace(' ','_')])
    labels=[Q(r['Churn']) for r in rawrows]
else:labels=[Q(r['churn']) for r in CH]
p=avg(labels);a=p*(1-p);assert len(labels)==3150 and sum(labels)==495 and p==Q(11,70)
path=DATA/'actual-Iranian-customers-usage-and-month12-churn.csv';S=read(path);note(path,'selected actual usage and month12 labels checked');assert len(S)==3150
keys={'seconds_of_use':'reported_first9months_seconds_of_use','frequency_of_use':'reported_first9months_call_frequency','frequency_of_sms':'reported_first9months_SMS_frequency','complains':'reported_first9months_complaint_indicator','churn':'reported_month12_churn_indicator'}
for o,r in zip(CH,S):
    assert o['row_id']==r['source_row_id']
    for original,key in keys.items():same(Q(o[original]),r[key])
pairvalues=[];path=DATA/'exact-sixteen-chosen-quarter-pairs-and-variance-estimators.csv';S=read(path);note(path,'all16 assumed ordered quarter pairs checked');assert len(S)==16
for i,aa in enumerate(h):
    for j,bb in enumerate(h):
        r=S[4*i+j];mean=(aa+bb)/2;v=((aa-mean)**2+(bb-mean)**2)/2;u=2*v
        assert r['first_actual_quarter']==quarters[i] and r['second_actual_quarter']==quarters[j]
        for value,key in [(mean,'sample_mean_exact'),(v,'variance_divide_by_n_exact'),(u,'variance_divide_by_n_minus_one_exact'),((v-hv)**2,'squared_error_divide_by_n_exact'),((u-hv)**2,'squared_error_divide_by_n_minus_one_exact')]:same(value,r[key])
        pairvalues.append((v,u))
expected={}
def store(case,rule,n,target,ex,v):expected[(case,rule,n)]={'expectation':ex,'bias':ex-target,'variance':v,'MSE':v+(ex-target)**2}
for n in [2,4,10,30,100,1000]:
    uvar=(h4-Q(n-3,n-1)*hv*hv)/n;store('country','sample_variance_divide_by_n_minus_one',n,hv,hv,uvar);store('country','sample_variance_divide_by_n',n,hv,Q(n-1,n)*hv,Q(n-1,n)**2*uvar)
for n in [1,2,5,10,30,100,1000]:
    store('person','sample_mean_of_log_wage',n,wmu,wmu,wv/n);store('person','first_draw_only',n,wmu,wmu,wv);store('person','sample_mean_plus_assumed_0point1',n,wmu,wmu+Q(1,10),wv/n)
    store('company','sample_churn_proportion',n,p,p,a/n);store('company','add_one_over_n_plus_two',n,p,(n*p+1)/(n+2),n*a/(n+2)**2)
path=DATA/'exact-chosen-estimator-expectation-bias-variance-and-MSE.csv';S=read(path);note(path,'47 estimator settings checked against actual-source recomputation');assert len(S)==len(expected)==47
for r in S:
    case,rule,n=r['case'],r['specified_estimator_rule'],int(r['chosen_iid_replacement_sample_size_n']);z=expected[(case,rule,n)]
    for key,value in z.items():same(value,r[key+'_exact']);add(case+'_'+rule+'_n'+str(n)+'_'+key,value)
path=DATA/'exact-chosen-customer-binomial-laws-and-two-estimates.csv';S=read(path);note(path,'154 outcomes independently checked and risk summed');assert len(S)==154
for n in [1,2,5,10,30,100]:
    rows=[r for r in S if int(r['chosen_iid_sample_size_n'])==n];assert len(rows)==n+1;total=Q(0);m0=Q(0);m1=Q(0)
    for k,r in enumerate(rows):
        prob=Q(math.comb(n,k))*p**k*(1-p)**(n-k);t0=Q(k,n);t1=Q(k+1,n+2);e0=(t0-p)**2;e1=(t1-p)**2
        assert int(r['churn_count_k'])==k
        for value,key in [(prob,'exact_binomial_count_probability'),(t0,'ordinary_sample_proportion_exact'),(t1,'add_one_estimate_exact'),(e0,'ordinary_squared_error_exact'),(e1,'add_one_squared_error_exact')]:same(value,r[key])
        total+=prob;m0+=prob*e0;m1+=prob*e1
    assert total==1 and m0==expected[('company','sample_churn_proportion',n)]['MSE'] and m1==expected[('company','add_one_over_n_plus_two',n)]['MSE']
    add('company_direct_sum_n'+str(n)+'_ordinary_MSE',m0);add('company_direct_sum_n'+str(n)+'_add_one_MSE',m1)
for key,value in {'housing_actual_retained_quarters':len(H),'housing_selected2024_quarters':len(h),'housing_fixed_mean_index_points':hmu,'housing_fixed_variance_index_points2':hv,'housing_fourth_central_moment_index_points4':h4,'housing_pair16_biased_expectation':avg([v for v,u in pairvalues]),'housing_pair16_unbiased_expectation':avg([u for v,u in pairvalues]),'housing_pair16_biased_MSE':avg([(v-hv)**2 for v,u in pairvalues]),'housing_pair16_unbiased_MSE':avg([(u-hv)**2 for v,u in pairvalues]),'people_original_rows':len(C),'people_valid_source_trimmed_log_wages':wn,'people_unobserved_log_wages':len(C)-wn,'people_fixed_unweighted_mean_log_wage':wmu,'people_fixed_variance_log_wage':wv,'customer_actual_records':len(labels),'customer_actual_churn_labels':sum(labels),'customer_fixed_empirical_rate':p}.items():add(key,value)
rpath=ROOT/'stat10-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():assert abs(R[key]-value)<=1e-10*max(1,abs(value)),(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)
(ROOT/'stat10-results.json').write_text(json.dumps({'chapter':'STAT-10','metrics':METRICS,'exactFractions':EXACT,'inputAudit':AUDIT,'checks':CHECKS,'interpretation':'Actual retained records are compared directly with original public XML/ZIP files when available. Empirical-law estimator risks are exact classroom sampling evaluations; original field iid, missing wages, survey representativeness, causal schooling effects and future churn predictions are not certified. Variance-estimator MSE uses index-point^4 units; person target is mean source log wage, not mean wage levels.'},ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('STAT-10:',len(METRICS),'metrics; original-data checks and estimator-risk calculations passed. R comparisons:',CHECKS['RmetricComparisons'])
