"""STAT-14: 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/'stats14-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



"""Stdlib numerical Student-t probabilities; not a data or case-result input.

Decimal Stirling normalization avoids large-df lgamma subtraction. A transformed,
scaled density integral computes survival probabilities directly, avoiding 1-CDF
cancellation. Published lesson values remain labeled numerical approximations.
"""
import math
from decimal import Decimal,localcontext
from functools import lru_cache
from statistics import NormalDist

def adaptive_integral(f,a,b,tolerance=2e-13,max_depth=28):
    fa,fb=f(a),f(b);mid=(a+b)/2;fm=f(mid);whole=(b-a)*(fa+4*fm+fb)/6
    def step(a,b,fa,fm,fb,whole,tol,depth):
        mid=(a+b)/2;leftmid=(a+mid)/2;rightmid=(mid+b)/2
        fl,fr=f(leftmid),f(rightmid)
        left=(mid-a)*(fa+4*fl+fm)/6;right=(b-mid)*(fm+4*fr+fb)/6
        delta=left+right-whole
        if abs(delta)<=15*tol:return left+right+delta/15
        if depth<=0:raise ArithmeticError('Adaptive integration did not converge')
        return step(a,mid,fa,fl,fm,left,tol/2,depth-1)+step(mid,b,fm,fr,fb,right,tol/2,depth-1)
    return step(a,b,fa,fm,fb,whole,tolerance,max_depth)

def _loggamma_without_constant(value):
    """logGamma minus .5*log(2*pi), with arguments shifted to at least64."""
    with localcontext() as ctx:
        ctx.prec=80;x=Decimal(str(value));correction=Decimal(0)
        while x<64:correction+=x.ln();x+=1
        pairs=[(1,6),(-1,30),(1,42),(-1,30),(5,66),(-691,2730),(7,6),(-3617,510),(43867,798),(-174611,330)]
        series=sum((Decimal(a)/b/(2*k*(2*k-1)*x**(2*k-1)) for k,(a,b) in enumerate(pairs,1)),Decimal(0))
        return (x-Decimal('.5'))*x.ln()-x+series-correction

@lru_cache(maxsize=256)
def student_log_normalizer(df):
    if not df>0:raise ValueError('Positive degrees of freedom required')
    with localcontext() as ctx:
        ctx.prec=80;nu=Decimal(str(df))
        ratio=_loggamma_without_constant((nu+1)/2)-_loggamma_without_constant(nu/2)
    return float(ratio)-.5*math.log(float(df)*math.pi)

def student_sf(t,df):
    """Upper-tail probability with direct scaled density integration."""
    t=float(t);df=float(df)
    if df<=0:raise ValueError('Positive degrees of freedom required')
    if t<0:return 1-student_sf(-t,df)
    if t==0:return .5
    if math.isinf(t):return 0.
    if df==1:return math.atan(1/t)/math.pi
    if df<=1:raise ValueError('This direct integral is used only for df>=1')
    base=math.log1p(t*t/df);logpdf=student_log_normalizer(df)-(df+1)*base/2
    def integrand(u):
        if u==1:return 0.
        x=t+u/(1-u)
        logratio=-(df+1)*(math.log1p(x*x/df)-base)/2-2*math.log1p(-u)
        return math.exp(logratio)
    tail=math.exp(logpdf)*adaptive_integral(integrand,0.,1.)
    if not 0<=tail<=.5+1e-12:raise ArithmeticError('Invalid Student-t upper tail')
    return min(.5,max(0.,tail))

@lru_cache(maxsize=256)
def student_quantile(probability,df):
    if not 0<probability<1:raise ValueError('Quantile probability must be inside(0,1)')
    if probability==.5:return 0.
    if probability<.5:return -student_quantile(1-probability,df)
    target=1-probability;left=0.;right=2.
    while student_sf(right,df)>target:right*=2
    for _ in range(56):
        mid=(left+right)/2
        if student_sf(mid,df)>target:left=mid
        else:right=mid
    return (left+right)/2

def normal_quantile(probability):return NormalDist().inv_cdf(probability)

def f_sf(value,df1,df2):
    """Scaled incomplete-beta upper F tail, used with df2>=2; binary64 output."""
    if value<0 or df1<=0 or df2<2:raise ValueError('Require value>=0, df1>0, df2>=2')
    if value==0:return 1.
    a,b=df2/2,df1/2;x=df2/(df2+df1*value)
    if x==0:return 0.
    if x==1:return 1.
    with localcontext() as ctx:
        ctx.prec=80
        logbeta=float(_loggamma_without_constant(a)+_loggamma_without_constant(b)-_loggamma_without_constant(a+b))+.5*math.log(2*math.pi)
    base=math.log1p(-x)
    def integrand(u):
        if u==0:return 0. if a>1 else math.exp(-(b-1)*base)
        return math.exp((a-1)*math.log(u)+(b-1)*(math.log1p(-x*u)-base))
    tail=math.exp(a*math.log(x)+(b-1)*base-logbeta)*adaptive_integral(integrand,0.,1.)
    if not 0<=tail<=1+1e-11:raise ArithmeticError('Invalid F tail')
    return min(1.,max(0.,tail))

def avg(v):return sum(v,Q(0))/len(v)
def sv(v):
    m=avg(v);return sum(((x-m)**2 for x in v),Q(0))/(len(v)-1)
def field(line,a,b):
    s=line[a-1:b].strip();return None if s in ['','.'] else Q(s)
def test(v,ref):
    n=len(v);mu=avg(v);s2=sv(v);sd=math.sqrt(float(s2));se=sd/math.sqrt(n);diff=mu-ref;t=float(diff)/se;p=2*student_sf(abs(t),n-1);crit=student_quantile(.975,n-1)
    return dict(n=n,df=n-1,mean_exact=mu,reference_exact=ref,difference_exact=diff,sample_variance_exact=s2,SD_approx=sd,SE_approx=se,t_approx=t,two_sided_p_approx=p,standardized_mean_difference_approx=float(diff)/sd,CI95_difference_lower_approx=float(diff)-crit*se,CI95_difference_upper_approx=float(diff)+crit*se)
raw=WORKSPACE/'work/textbooks-2026/raw';H=read(COMMON/'korea-housing.csv');note(COMMON/'korea-housing.csv','retained actual BIS observations');hp=raw/'korea-housing-real.csv'
if hp.is_file():
    note(hp,'original SDMX XML',True);tree=ET.fromstring(hp.read_text(encoding='utf-8'));o={e.attrib['TIME_PERIOD']:Q(e.attrib['OBS_VALUE']) for e in tree.iter() if e.tag.endswith('Obs')};assert len(o)==len(H)==180
    for r in H:same(o[r['quarter']],r['real'])
else:o={r['quarter']:Q(r['real']) for r in H}
h=[o['2024-Q'+str(i)] for i in range(1,5)];hm=avg(h);hv=sum(((x-hm)**2 for x in h),Q(0))/4
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

U=read(COMMON/'churn.csv');note(COMMON/'churn.csv','actual retained3150 telecom records');archive=raw/'churn.zip'
if archive.is_file():
    note(archive,'original UCI Customer Churn.csv',True)
    with zipfile.ZipFile(archive) as z:source=list(csv.DictReader(io.StringIO(z.read('Customer Churn.csv').decode('utf-8-sig'))))
    assert len(U)==len(source)==3150
    for i,(r,o) in enumerate(zip(U,source),1):
        assert int(r['row_id'])==i
        for k,v in o.items():same(Q(v),r[k.strip().lower().replace(' ','_')])

def cells(matrix,rowlabels,columnlabels):
    n=sum(map(sum,matrix));rt=list(map(sum,matrix));ct=[sum(r[j] for r in matrix) for j in range(len(columnlabels))];out=[]
    for i,label in enumerate(rowlabels):
        for j,col in enumerate(columnlabels):
            o=matrix[i][j];e=Q(rt[i]*ct[j],n);out.append(dict(row_category=label,column_category=col,observed_count=o,row_total=rt[i],column_total=ct[j],grand_total=n,independence_expected_count_exact=e,observed_row_fraction_exact=Q(o,rt[i]),Pearson_contribution_exact=(o-e)**2/e,Pearson_residual_approx=float(o-e)/math.sqrt(float(e))))
    chi=sum((r['Pearson_contribution_exact'] for r in out),Q(0));df=(len(rt)-1)*(len(ct)-1);return out,dict(n=n,rows=len(rt),columns=len(ct),degrees_of_freedom=df,Pearson_chi_squared_exact=chi,Cramer_V_approx=math.sqrt(float(chi/(n*min(len(rt)-1,len(ct)-1)))),minimum_expected_count_exact=min(r['independence_expected_count_exact'] for r in out))
def checkcells(filename,expected,prefix):
    S=read(DATA/filename);note(DATA/filename,'observed/expected cells independently reconstructed from original records');assert len(S)==len(expected)
    for i,(r,o) in enumerate(zip(S,expected)):
        assert r['row_category']==o['row_category'] and r['column_category']==o['column_category']
        for k,v in o.items():
            if k not in ['row_category','column_category']:near(v,r[k])
        for k in ['observed_count','independence_expected_count_exact','observed_row_fraction_exact','Pearson_contribution_exact','Pearson_residual_approx']:add(prefix+'_cell'+str(i)+'_'+k,o[k])
periods=[('1980-1999',1980,1999),('2000-2009',2000,2009),('2010-2024',2010,2024)];matrix=[];actual=[]
for label,lo,hi in periods:
    records=[r for r in H if lo<=int(r['year'])<=hi];high=sum(Q(r['real'])>100 for r in records);matrix.append([high,len(records)-high]);actual.extend((r,label) for r in records)
S=read(DATA/'actual180-quarters-and-defined-period-index-categories.csv');note(DATA/'actual180-quarters-and-defined-period-index-categories.csv','all180 actual quarters with explicitly derived teaching labels');assert len(S)==180
for r,(o,label) in zip(S,actual):assert r['quarter']==o['quarter'] and r['chosen_teaching_period']==label;same(Q(o['real']),r['reported_real_index_2010average100']);assert (r['derived_real_index_strictly_above100']=='True')==(Q(o['real'])>100)
hc,hs=cells(matrix,[p[0] for p in periods],['index_gt100','index_le100']);hs['chi2_reference_tail_approx_not_validated_time_series_p']=math.exp(-float(hs['Pearson_chi_squared_exact'])/2);checkcells('actual-period-by-index-six-observed-expected-cells.csv',hc,'housing')
S=read(DATA/'actual-housing-categorical-association-summary.csv');note(DATA/'actual-housing-categorical-association-summary.csv','descriptive association and unvalidated reference tail')
for k,v in hs.items():near(v,S[0][k]);add('housing_'+k,v)
def band(e):return 'years_le11' if e<=11 else 'years_eq12' if e==12 else 'years13to15' if e<=15 else 'years_ge16'
labels=['years_le11','years_eq12','years13to15','years_ge16'];S=read(DATA/'actual3613-person-records-and-derived-education-bands.csv');note(DATA/'actual3613-person-records-and-derived-education-bands.csv','all3613 actual person rows and603 missing logs')
for o,r in zip(people,S):
    same(o['person'],r['source_person_ID']);same(o['education'],r['reported_education_years']);assert r['derived_teaching_year_band']==band(o['education'])
    if o['log_wage'] is None:assert r['source_trimmed_log_wage']==''
    else:same(o['log_wage'],r['source_trimmed_log_wage'])
grand=avg(w);ssb=ssw=Q(0);fits={};S=read(DATA/'actual-four-education-band-log-wage-moments.csv');note(DATA/'actual-four-education-band-log-wage-moments.csv','four actual year-band moments')
for label,r in zip(labels,S):
    allrows=[o for o in people if band(o['education'])==label];v=[o['log_wage'] for o in allrows if o['log_wage'] is not None];m=avg(v);fits[label]=m;within=sum(((x-m)**2 for x in v),Q(0));between=len(v)*(m-grand)**2;ssw+=within;ssb+=between;vals=dict(all_actual_records=len(allrows),available_source_log_wages=len(v),missing_source_log_wages=len(allrows)-len(v),group_mean_log_wage_exact=m,sample_variance_log_wage_exact=sv(v),within_group_SS_exact=within,between_group_SS_contribution_exact=between)
    for k,x in vals.items():near(x,r[k]);add('people_'+label+'_'+k,x)
sst=sum(((x-grand)**2 for x in w),Q(0));assert sst==ssb+ssw;n=len(w);k=4;mb=ssb/3;mw=ssw/(n-4);f=mb/mw
S=read(DATA/'actual3010-within-band-fits-and-residuals.csv');note(DATA/'actual3010-within-band-fits-and-residuals.csv','all3010 fitted observed group means and exact residuals');observed=[o for o in people if o['log_wage'] is not None];assert len(S)==len(observed)==3010
for r,o in zip(S,observed):
    value=o['log_wage'];fit=fits[band(o['education'])];e=value-fit;same(o['person'],r['source_person_ID']);same(value,r['actual_source_log_wage']);same(fit,r['fitted_observed_group_mean_exact']);same(e,r['within_group_residual_exact']);same(e*e,r['within_residual_squared_exact']);same(value-grand,r['grand_centered_actual_value_exact'])
S=read(DATA/'actual-one-way-ANOVA-sum-of-squares-table.csv');note(DATA/'actual-one-way-ANOVA-sum-of-squares-table.csv','three exact ANOVA table components');assert len(S)==3
for r,df,ss in zip(S,[3,n-4,n-1],[ssb,ssw,sst]):same(Q(df),r['df']);same(ss,r['sum_of_squares_exact'])
vals=dict(n_observed_log_wages=n,number_of_defined_bands=4,grand_mean_log_wage_exact=grand,between_SS_exact=ssb,within_SS_exact=ssw,total_SS_exact=sst,between_df=3,within_df=n-4,total_df=n-1,between_MS_exact=mb,within_MS_exact=mw,classical_F_exact_from_observed_sums=f,classical_F_reference_tail_approx=f_sf(float(f),3,n-4),observed_eta_squared_exact=ssb/sst)
S=read(DATA/'actual-one-way-ANOVA-summary-and-working-tail.csv');note(DATA/'actual-one-way-ANOVA-summary-and-working-tail.csv','classical working-model F tail computed without1-CDF cancellation')
for key,v in vals.items():near(v,S[0][key]);add('people_ANOVA_'+key,v)
S=read(DATA/'actual3150-customer-complaint-and-churn-records.csv');note(DATA/'actual3150-customer-complaint-and-churn-records.csv','all3150 actual binary pairs');assert len(S)==3150
for o,r in zip(U,S):same(Q(o['row_id']),r['source_row_id']);same(Q(o['complains']),r['actual_first9months_complaint_flag']);same(Q(o['churn']),r['actual_month12_churn_flag'])
cm=[]
for g in [1,0]:
    records=[r for r in U if Q(r['complains'])==g];e=sum(int(Q(r['churn'])) for r in records);cm.append([e,len(records)-e])
cc,cs=cells(cm,['complaint1','complaint0'],['churn1','churn0']);p1=Q(cm[0][0],sum(cm[0]));p0=Q(cm[1][0],sum(cm[1]));pooled=Q(cm[0][0]+cm[1][0],3150);z2=(p1-p0)**2/(pooled*(1-pooled)*(Q(1,sum(cm[0]))+Q(1,sum(cm[1]))));assert z2==cs['Pearson_chi_squared_exact'];cs.update(chi2_reference_tail_approx=math.erfc(math.sqrt(float(z2)/2)),observed_churn_fraction_difference_exact=p1-p0,pooled_two_proportion_z_squared_exact=z2)
checkcells('actual-four-complaint-churn-observed-expected-cells.csv',cc,'customers');S=read(DATA/'actual-customer-Pearson-and-two-proportion-identity.csv');note(DATA/'actual-customer-Pearson-and-two-proportion-identity.csv','exact no-correction Pearson=z squared identity')
for key,v in cs.items():near(v,S[0][key]);add('customers_'+key,v)

rpath=ROOT/'stat14-r-results.csv'
if rpath.is_file():
    R={r['metric']:float(r['value']) for r in read(rpath)};assert set(R)==set(METRICS),(set(R)-set(METRICS),set(METRICS)-set(R))
    for k,v in METRICS.items():
        near(v,R[k])
        if 0<abs(v)<1e-9:assert abs(R[k]/v-1)<=1e-8,(k,R[k],v)
    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/'stat14-results.json').write_text(json.dumps({'chapter':'STAT-14','metrics':METRICS,'exactFractions':EXACT,'numericalApproximationMetrics':APPROX,'inputAudit':AUDIT,'checks':CHECKS,'interpretation':'Actual source records are numeric inputs. All actual observations and exact table/decomposition quantities are numeric inputs, not case JSON results. Quarter categories preserve time dependence and do not certify an iid chi-square model. Classical ANOVA references require separate normal/independent/equal-variance assumptions. Education or complaint intervention effects are not identified. All nonzero tiny metrics are cross-checked by relative error against base R.'},ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8');print('STAT-14:',len(METRICS),'independent actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
