"""STAT-11: 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/'stats11-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(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 var(v):return avg([(x-avg(v))**2 for x in v])
def sv(v):return sum(((x-avg(v))**2 for x in v),Q(0))/(len(v)-1)
def flag(s):assert s in ['True','False'];return s=='True'
def summary(v):
    n=len(v);mu=avg(v);vs=sv(v);sd=math.sqrt(float(vs));se=sd/math.sqrt(n);t=student_quantile(.975,n-1)
    return dict(n=n,mean=mu,sample_variance=vs,SD=sd,SE=se,t975=t,df=n-1,CI_lower=float(mu)-t*se,CI_upper=float(mu)+t*se,PI_lower=float(mu)-t*sd*math.sqrt(1+1/n),PI_upper=float(mu)+t*sd*math.sqrt(1+1/n))
raw=WORKSPACE/'work/textbooks-2026/raw'
H=read(COMMON/'korea-housing.csv');note(COMMON/'korea-housing.csv','retained BIS real-index observations')
hr=raw/'korea-housing-real.csv'
if hr.is_file():
    note(hr,'original BIS SDMX XML',True);tree=ET.fromstring(hr.read_text(encoding='utf-8'));source={e.attrib['TIME_PERIOD']:Q(e.attrib['OBS_VALUE']) for e in tree.iter() if e.tag.endswith('Obs')}
    assert len(source)==len(H)==180
    for r in H:same(source[r['quarter']],r['real'])
else:source={r['quarter']:Q(r['real']) for r in H}
quarters=['2024-Q'+str(i) for i in range(1,5)];h=[source[q] for q in quarters];mu=avg(h);v=var(h)
P=DATA/'actual-Korea2024-real-index-fixed-target.csv';S=read(P);note(P,'four complete fixed-target values');assert len(S)==4
for r,x in zip(S,h):same(x,r['reported_real_index_2010average100']);same(mu,r['known_complete_four_quarter_mean_exact']);same(v,r['known_complete_four_quarter_variance_exact'])
rs=read(DATA/'all-assumed-four-quarter-resamples-and-reference-mean-intervals.csv');ps=read(DATA/'all-assumed-resample-next-draw-tuples-and-reference-prediction-intervals.csv');cs=read(DATA/'exact-finite-reference-rule-coverage-and-widths.csv')
for name in ['all-assumed-four-quarter-resamples-and-reference-mean-intervals.csv','all-assumed-resample-next-draw-tuples-and-reference-prediction-intervals.csv','exact-finite-reference-rule-coverage-and-widths.csv']:note(DATA/name,'assumed finite resampling rule recalculated from original actual values')
assert (len(rs),len(ps),len(cs))==(768,3072,3)
for li,level in enumerate([.90,.95,.99]):
    z=normal_quantile((1+level)/2);zq=Q(str(z));half2=zq*zq*v/4;pi2=zq*zq*v*Q(5,4);half=math.sqrt(float(half2));pihalf=math.sqrt(float(pi2));cc=pc=0
    for si,idx in enumerate(itertools.product(range(4),repeat=4)):
        sm=avg([h[i] for i in idx]);r=rs[li*256+si];inc=(sm-mu)**2<=half2;cc+=inc
        same(sm,r['sample_mean_exact']);assert flag(r['covers_known_fixed_mean_exact_comparison'])==inc;assert not flag(r['is_new_observed_time_series']);near(float(sm)-half,r['reference_mean_CI_lower_approx']);near(float(sm)+half,r['reference_mean_CI_upper_approx'])
        for ni,x in enumerate(h):
            r=ps[li*1024+4*si+ni];inc=(x-sm)**2<=pi2;pc+=inc;same(x,r['drawn_stored_index_value_exact']);assert flag(r['contains_assumed_next_independent_draw_exact_comparison'])==inc;assert not flag(r['is_actual_future_quarter_observed']);near(float(sm)-pihalf,r['reference_prediction_lower_approx']);near(float(sm)+pihalf,r['reference_prediction_upper_approx'])
    r=cs[li];same(Q(cc,256),r['exact_mean_rule_coverage']);same(Q(pc,1024),r['exact_prediction_rule_coverage']);near(half,r['known_variance_mean_halfwidth_approx']);near(pihalf,r['known_variance_new_draw_halfwidth_approx'])
    for key,value in dict(z=z,CI_coverage=Q(cc,256),PI_coverage=Q(pc,1024),CI_halfwidth=half,PI_halfwidth=pihalf).items():add('housing_level'+str(int(level*100))+'_'+key,value)
for key,value in dict(actual_quarters=len(H),known2024_mean=mu,known2024_variance=v).items():add('housing_'+key,value)
C=read(COMMON/'college-proximity.csv');note(COMMON/'college-proximity.csv','retained anonymized actual people');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):
    x=line[a-1:b].strip();return None if x in ['','.'] else Q(x)
if archive.is_file():
    note(archive,'original Card nls.dat and codebook',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(C)==len(lines)==3613 and 'outliers trimmed' in book
    original=[{k:field(line,a,b) for k,a,b in spec} for line in lines]
    for r,o in zip(C,original):
        for k,a,b in spec:
            if o[k] is None:assert r[k]==''
            else:same(o[k],r[k])
else:original=[{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 original if r['log_wage'] is not None];ws=summary(w);assert len(w)==3010
P=DATA/'actual-1976-log-wages-with-all-original-missing-records.csv';S=read(P);note(P,'all actual people with missing log wages preserved');assert len(S)==3613
for o,r in zip(original,S):
    same(o['person'],r['source_person_ID']);assert flag(r['log_wage_available'])==(o['log_wage'] is not None)
    if o['log_wage'] is None:assert r['reported_source_trimmed_log_wage']==''
    else:same(o['log_wage'],r['reported_source_trimmed_log_wage'])
P=DATA/'actual-log-wage-working-mean-and-new-draw-intervals.csv';S=read(P);note(P,'two working-model intervals independently recalculated');assert len(S)==2
for i,r in enumerate(S):same(ws['mean'],r['observed_sample_mean_exact']);same(ws['sample_variance'],r['observed_sample_variance_exact']);near(ws['t975'],r['t975_critical_approx']);near(ws['CI_lower' if i==0 else 'PI_lower'],r['lower_bound_approx']);near(ws['CI_upper' if i==0 else 'PI_upper'],r['upper_bound_approx'])
for key,value in ws.items():add('people_'+key,value)
add('people_original_rows',len(C));add('people_missing_log_wages',len(C)-len(w));add('people_descriptive_in_sample_PI_fraction',Q(sum(ws['PI_lower']<=float(x)<=ws['PI_upper'] for x in w),len(w)))
NJ=read(COMMON/'nj-minwage.csv');note(COMMON/'nj-minwage.csv','retained actual stores and both waves');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 records and SAS',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
    records=[{k:field(line,a,b) for k,a,b in spec} for line in lines]
    for o,r in zip(records,NJ):
        for k,a,b in spec:
            if o[k] is None:assert r[k]==''
            else:same(o[k],r[k])
else:records=[{k:Q(r[k]) if r[k] else None for k,a,b in spec} for r in NJ]
for o in records:
    for suffix in ['before','after']:
        ks=['ft_'+suffix,'pt_'+suffix,'managers_'+suffix];o['fte_'+suffix]=o[ks[0]]+o[ks[1]]/2+o[ks[2]] if all(o[k] is not None for k in ks) else None
P=DATA/'actual-NJ-PA-stores-and-preserved-paired-FTE-changes.csv';S=read(P);note(P,'410 actual stores and incomplete pairs checked');assert len(S)==410
for source_row_id,(o,r) in enumerate(zip(records,S),1):
    same(Q(source_row_id),r['source_row_id']);same(o['store'],r['source_store_ID']);ok=o['fte_before'] is not None and o['fte_after'] is not None;assert flag(r['both_FTE_observed'])==ok
    if ok:same(o['fte_after']-o['fte_before'],r['actual_paired_FTE_change_exact'])
    else:assert r['actual_paired_FTE_change_exact']==''
P=DATA/'actual-complete-pair-store-moments-and-working-intervals.csv';S=read(P);note(P,'paired change summaries and covariance identities');assert len(S)==3
for label,state,r in zip(['all','NJ','PA'],[None,1,0],S):
    pairs=[o for o in records if o['fte_before'] is not None and o['fte_after'] is not None and(state is None or o['nj']==state)];a=[o['fte_before'] for o in pairs];b=[o['fte_after'] for o in pairs];d=[bb-aa for aa,bb in zip(a,b)];ss=summary(d);cov=sum(((aa-avg(a))*(bb-avg(b)) for aa,bb in zip(a,b)),Q(0))/(len(a)-1);assert sv(d)==sv(a)+sv(b)-2*cov
    same(ss['mean'],r['mean_exact']);same(ss['sample_variance'],r['sample_variance_exact']);same(cov,r['before_after_sample_covariance_exact']);near(ss['SE'],r['estimated_SE_of_mean_approx']);near(ss['CI_lower'],r['mean_CI_lower_approx']);near(ss['CI_upper'],r['mean_CI_upper_approx']);ind=math.sqrt(float((sv(a)+sv(b))/len(a)));near(ind,r['incorrect_independent_wave_SE_reference_approx'])
    for key,value in ss.items():add('stores_'+label+'_'+key,value)
    add('stores_'+label+'_before_after_sample_covariance',cov);add('stores_'+label+'_incorrect_independent_wave_SE',ind)
add('stores_original_rows',len(records));add('stores_incomplete_pairs',len(records)-int(METRICS['stores_all_n']))
rpath=ROOT/'stat11-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/'stat11-results.json').write_text(json.dumps({'chapter':'STAT-11','metrics':METRICS,'exactFractions':EXACT,'numericalApproximationMetrics':APPROX,'inputAudit':AUDIT,'checks':CHECKS,'interpretation':'The completely observed housing target has no invented sampling uncertainty. Coverage is exact only under the separately specified finite replacement law. Student-t interval formulas require working iid normal assumptions; large n alone does not validate a normal individual prediction interval. Store paired changes are descriptive and not identified causal policy effects. Normal/t quantiles and interval endpoints are numerical approximations; actual moments and finite tuple counts are exact rational calculations.'},ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('STAT-11:',len(METRICS),'actual-source and interval metrics; R comparisons',CHECKS['RmetricComparisons'])
