"""STAT-12: 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/'stats12-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 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
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])

alt=[Q(1,2),Q(1,4),Q(1,8),Q(1,8)];am=sum((x*p for x,p in zip(h,alt)),Q(0));tuples=[]
for idx in itertools.product(range(4),repeat=4):
    sm=avg([h[i] for i in idx]);tuples.append((sm,(sm-hm)**2,math.prod(alt[i] for i in idx)))
pvalues=[Q(sum(b>=a for sm,b,p in tuples),256) for sm,a,p in tuples];assert sum((p for sm,a,p in tuples),Q(0))==1
S=read(DATA/'all256-assumed-null-tuples-and-exact-p-values.csv');note(DATA/'all256-assumed-null-tuples-and-exact-p-values.csv','all exact p-values independently enumerated');assert len(S)==256
for r,(sm,a,pr),pv in zip(S,tuples,pvalues):same(sm,r['sample_mean_exact']);same(a,r['absolute_mean_deviation_squared_exact']);same(pr,r['assumed_alternative_tuple_probability_exact']);same(pv,r['exact_two_sided_null_p_value'])
S=read(DATA/'chosen-three-error-power-rules.csv');note(DATA/'chosen-three-error-power-rules.csv','error and power recomputed under specified laws');assert len(S)==3
for alpha,r in zip([Q(1,100),Q(1,20),Q(1,10)],S):
    z=normal_quantile(1-float(alpha)/2);threshold=Q(str(z))**2*hv/4;size=Q(sum(a>threshold for sm,a,p in tuples),256);power=sum((p for sm,a,p in tuples if a>threshold),Q(0));es=Q(sum(p<=alpha for p in pvalues),256);ep=sum((p for (sm,a,p),pv in zip(tuples,pvalues) if pv<=alpha),Q(0));assert es<=alpha
    vals=dict(normal_reference_critical_approx=z,normal_reference_actual_type_I_error_exact=size,normal_reference_assumed_alternative_power_exact=power,normal_reference_assumed_alternative_type_II_error_exact=1-power,exact_p_rule_actual_type_I_error_exact=es,exact_p_rule_assumed_alternative_power_exact=ep)
    for k,v in vals.items():near(v,r[k]);add('housing_alpha'+str(float(alpha))+'_'+k,v)
for k,v in dict(known_mean=hm,known_variance=hv,chosen_alternative_mean=am,actual_retained_rows=len(H),actual_selected_quarters=4).items():add('housing_'+k,v)
S=read(DATA/'actual-four-quarters-and-explicit-null-alternative-laws.csv');note(DATA/'actual-four-quarters-and-explicit-null-alternative-laws.csv','actual quarters and chosen laws checked');assert len(S)==4
for r,x,a in zip(S,h,alt):same(x,r['reported_real_index_2010average100']);same(a,r['chosen_alternative_ticket_probability_exact'])
S=read(DATA/'actual-people-log-wages-with-missing-records.csv');note(DATA/'actual-people-log-wages-with-missing-records.csv','all actual people and603 missing values checked');assert len(S)==3613
for o,r in zip(people,S):
    same(o['person'],r['source_person_ID'])
    if o['log_wage'] is None:assert r['reported_source_trimmed_log_wage']==''
    else:same(o['log_wage'],r['reported_source_trimmed_log_wage'])
S=read(DATA/'actual-log-wage-tests-against-chosen-references.csv');note(DATA/'actual-log-wage-tests-against-chosen-references.csv','four hypothetical reference tests recomputed')
for ref,r in zip([Q(31,5),Q(25,4),Q(63,10),Q(127,20)],S):
    for k,v in test(w,ref).items():near(v,float(Q(r[k])));add('people_ref'+str(float(ref))+'_'+k,v)
S=read(DATA/'actual-store-pair-changes-with-incomplete-records.csv');note(DATA/'actual-store-pair-changes-with-incomplete-records.csv','actual pairs retained without zero filling');assert len(S)==410
for source_row_id,(o,r) in enumerate(zip(stores,S),1):
    same(Q(source_row_id),r['source_row_id']);assert r['state']==('NJ' if o['nj']==1 else 'PA')
    ok=o['fte_before'] is not None and o['fte_after'] is not None
    if ok:same(o['fte_after']-o['fte_before'],r['paired_change_exact'])
    else:assert r['paired_change_exact']==''
S=read(DATA/'actual-paired-store-change-tests-and-effect-sizes.csv');note(DATA/'actual-paired-store-change-tests-and-effect-sizes.csv','three working paired tests and effect magnitudes')
for label,state,r in zip(['all','NJ','PA'],[None,1,0],S):
    d=[o['fte_after']-o['fte_before'] for o in stores if o['fte_before'] is not None and o['fte_after'] is not None and(state is None or o['nj']==state)]
    for k,v in test(d,Q(0)).items():near(v,float(Q(r[k])));add('stores_'+label+'_'+k,v)
add('people_original_rows',len(people));add('people_unobserved_log_wages',len(people)-len(w));add('stores_original_rows',len(stores));add('assumed_ten_independent_5pct_tests_family_error',1-(1-.05)**10)

rpath=ROOT/'stat12-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])
    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/'stat12-results.json').write_text(json.dumps({'chapter':'STAT-12','metrics':METRICS,'exactFractions':EXACT,'numericalApproximationMetrics':APPROX,'inputAudit':AUDIT,'checks':CHECKS,'interpretation':'Actual source records are numeric inputs. Ticket null/alternative probabilities and reference log wages are explicitly assumed classroom laws, not observed policy changes. Exact finite error/power and working t p-values are distinct; policy causality and representative iid sampling are not certified.'},ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8');print('STAT-12:',len(METRICS),'independent actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
