"""STAT-18: 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/'stats18-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

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(' ','_')])
"""Integer-parameter Beta density and quantiles via positive binomial tails.

No observed data or case-result inputs. At a,b positive integers,
I_x(a,b)=Pr(Binomial(a+b-1,x)>=a). Sum the appropriate positive tail;
use symmetry for the large tail and bisection for the interior quantile.
"""
from decimal import Decimal,localcontext
from math import comb

def beta_density(x,a,b):
    with localcontext() as ctx:
        ctx.prec=150;x=Decimal(x)
        assert a>=1 and b>=1 and 0<=x<=1
        if x==0:return Decimal(b if a==1 else 0)
        if x==1:return Decimal(a if b==1 else 0)
        return +(Decimal(b*comb(a+b-1,a-1))*x**(a-1)*(1-x)**(b-1))

def beta_cdf(x,a,b):
    with localcontext() as ctx:
        ctx.prec=150;x=Decimal(x)
        assert a>=1 and b>=1 and 0<=x<=1
        if x==0:return Decimal(0)
        if x==1:return Decimal(1)
        if x>Decimal(a)/(a+b):return +(1-beta_cdf(1-x,b,a))
        n=a+b-1;j=a
        term=Decimal(comb(n,a))*x**a*(1-x)**(n-a);total=term
        while j<n:
            term*=Decimal(n-j)/Decimal(j+1)*x/(1-x);total+=term;j+=1
            if term<total*Decimal('1e-140'):break
        return +total

def beta_quantile(prob,a,b):
    with localcontext() as ctx:
        ctx.prec=120;prob=Decimal(prob);assert 0<prob<1
        lo=Decimal(0);hi=Decimal(1)
        for _ in range(240):
            mid=(lo+hi)/2
            if beta_cdf(mid,a,b)<prob:lo=mid
            else:hi=mid
        return +((lo+hi)/2)

def avg(v):return sum(v,Q(0))/len(v)
labels=[int(Q(r['life_expectancy'])>=80) for r in countries];n=len(labels);s=sum(labels);hat=Q(s,n)
def likelihood(p):return p**s*(1-p)**(n-s)
path=DATA/'actual16-country-period-life-expectancy-and-derived-binary-label.csv';S=read(path);note(path,'actual period life expectancy and independently derived threshold labels');assert len(S)==16
for r,o,label in zip(S,countries,labels):assert r['country']==o['country'];same(Q(o['life_expectancy']),r['actual2024_period_life_expectancy_years']);same(Q(label),r['derived_life_at_least80_label'])
path=DATA/'explicit-working-Bernoulli-likelihood-profile.csv';S=read(path);note(path,'exact working-likelihood values independently calculated');grid=sorted(set([Q(i,20) for i in range(1,20)]+[hat]));assert len(S)==len(grid)
for i,(p,r) in enumerate(zip(grid,S)):
 l=likelihood(p);ratio=l/likelihood(hat);same(p,r['assumed_Bernoulli_p_exact']);same(l,r['ordered_label_likelihood_exact']);same(ratio,r['relative_likelihood_to_continuous_MLE_exact']);add('country_grid'+str(i)+'_likelihood',l);add('country_grid'+str(i)+'_relative_likelihood',ratio)
add('country_actual_records',n);add('country_actual_derived_successes',s);add('country_working_Bernoulli_MLE',hat)
path=DATA/'two-chosen-discrete-priors-and-exact-posterior-update.csv';S=read(path);note(path,'chosen priors, evidence and posterior masses independently normalized');hyp=[Q(1,4),Q(1,2),Q(3,4)]
for name,prior in [('equal3',[Q(1,3)]*3),('chosen_low_weighted',[Q(1,2),Q(1,3),Q(1,6)])]:
 evidence=sum((p*likelihood(x) for p,x in zip(prior,hyp)),Q(0));posterior=[]
 for i,(p,x) in enumerate(zip(prior,hyp)):
  r=next(r for r in S if r['assumed_discrete_prior']==name and Q(r['hypothesis_p_exact'])==x);vals=dict(chosen_prior_mass_exact=p,same_ordered_label_likelihood_exact=likelihood(x),joint_prior_times_likelihood_exact=p*likelihood(x),prior_predictive_evidence_exact=evidence,posterior_mass_exact=p*likelihood(x)/evidence);posterior.append(vals['posterior_mass_exact'])
  for key,v in vals.items():same(v,r[key]);add('country_'+name+'_hyp'+str(i)+'_'+key,v)
 assert sum(posterior,Q(0))==1
path=DATA/'actual3613-person-records-preserving-unavailable-log-wages.csv';S=read(path);note(path,'all actual people and unavailable1976 source logs retained');assert len(S)==3613
for i,(o,r) in enumerate(zip(people,S),1):
 same(Q(i),r['sourceRow']);same(o['person'],r['source_person_code'])
 if o['log_wage'] is None:assert r['actual_source_trimmed1976_log_hourly_wage_cents']==''
 else:same(o['log_wage'],r['actual_source_trimmed1976_log_hourly_wage_cents'])
X=[o['log_wage'] for o in people if o['log_wage'] is not None];N=len(X);mu=avg(X);sse=sum((x*x for x in X),Q(0))-sum(X,Q(0))**2/N;vmle=sse/N;v1=sse/(N-1)
path=DATA/'working-normal-MLE-and-distinct-variance-denominators.csv';S=read(path);note(path,'exact raw-sum normal MLE and n-minus-one rule independently derived');vals=dict(all_original_people=len(people),available_source_logs=N,unavailable_source_logs=len(people)-N,working_normal_MLE_mean_exact=mu,observed_SSE_at_mean_exact=sse,working_normal_MLE_variance_divide_n_exact=vmle,sample_variance_divide_n_minus1_exact=v1,variance_ratio_n_over_n_minus1_exact=v1/vmle)
for key,v in vals.items():same(Q(v),S[0][key]);add('person_'+key,v)
path=DATA/'working-normal-profile-likelihood-over-chosen-mean-grid.csv';S=read(path);note(path,'profile likelihood ratios from actual source SSE, not from stored results');assert len(S)==21
for i,r in enumerate(S):
 delta=Q(i-10,100);queried=mu+delta;v=vmle+delta*delta;logratio=-D(N)/2*(D(v.numerator)/D(v.denominator)/(D(vmle.numerator)/D(vmle.denominator))).ln();ratio=logratio.exp();same(delta,r['assumed_mean_shift_exact']);same(queried,r['queried_normal_mean_exact']);same(v,r['profile_MLE_variance_at_mean_exact']);near(logratio,r['profile_log_likelihood_difference_decimal_approx']);near(ratio,r['profile_likelihood_ratio_decimal_approx']);add('person_profile'+str(i)+'_mean',queried);add('person_profile'+str(i)+'_variance',v);add('person_profile'+str(i)+'_log_likelihood_difference',float(logratio));add('person_profile'+str(i)+'_likelihood_ratio',float(ratio))
path=DATA/'actual3150-customer-records-full-source-fields.csv';S=read(path);note(path,'all retained actual customer records and fourteen source fields independently compared');assert len(S)==3150
for o,r in zip(U,S):
 for key,v in o.items():same(Q(v),r[key])
Y=[int(Q(r['churn'])) for r in U];priors=[(1,1),(2,2),(1,9)];path=DATA/'chosen-Beta-priors-with-actual-source-prefix-updates.csv';S=read(path);note(path,'actual prefix counts and chosen-model posterior moments independently recalculated');assert len(S)==18;final=[]
for size in [0,10,50,100,500,3150]:
 count=sum(Y[:size])
 for a,b in priors:
  A=a+count;B=b+size-count;T=A+B;pm=Q(A,T);pv=Q(A*B,T*T*(T+1));p2=Q(A*(A+1),T*(T+1));r=next(r for r in S if int(r['actual_source_prefix_records'])==size and int(r['chosen_prior_alpha'])==a and int(r['chosen_prior_beta'])==b);vals=dict(actual_source_prefix_records=size,actual_prefix_churn_count=count,chosen_prior_alpha=a,chosen_prior_beta=b,posterior_alpha=A,posterior_beta=B,posterior_mean_and_next1_predictive_exact=pm,posterior_variance_exact=pv,assumed_next2_both_churn_predictive_exact=p2,plug_in_squared_posterior_mean_exact=pm**2,next2_predictive_minus_plug_in_exact=p2-pm**2);assert p2-pm**2==pv
  for key,v in vals.items():same(Q(v),r[key]);add('customer_n'+str(size)+'_prior'+str(a)+'_'+str(b)+'_'+key,v)
  if size:same(Q(count,size),r['working_Bernoulli_MLE_exact'])
  else:assert r['working_Bernoulli_MLE_exact']==''
  if size==3150:final.append((a,b,A,B))
path=DATA/'working-Beta-posterior-summaries-and-equal-tail-intervals.csv';S=read(path);note(path,'posterior exact modes and positive-tail/bisection quantiles independently recomputed');assert len(S)==3
for (a,b,A,B),r in zip(final,S):
 mode=Q(A-1,A+B-2);lo=beta_quantile('0.025',A,B);hi=beta_quantile('0.975',A,B);same(mode,r['posterior_mode_exact']);near(lo,r['equal_tail_025_quantile_decimal_approx']);near(hi,r['equal_tail_975_quantile_decimal_approx']);add('customer_prior'+str(a)+'_'+str(b)+'_posterior_mode',mode);add('customer_prior'+str(a)+'_'+str(b)+'_q025',float(lo));add('customer_prior'+str(a)+'_'+str(b)+'_q975',float(hi))
path=DATA/'working-Beta-posterior-density-grid.csv';S=read(path);note(path,'integer-normalized posterior densities recomputed, not observed parameter measurements');assert len(S)==75
for i in range(20,45):
 x=Q(i,200)
 for a,b,A,B in final:
  r=next(r for r in S if Q(r['queried_parameter_p_exact'])==x and int(r['chosen_prior_alpha'])==a and int(r['chosen_prior_beta'])==b);value=beta_density(D(x.numerator)/D(x.denominator),A,B);stored=D(r['posterior_density_decimal_approx']);assert abs(value/stored-1)<D('1e-70');add('customer_density_grid'+str(i)+'_prior'+str(a)+'_'+str(b),float(value))
add('customers_actual_records',len(Y));add('customers_actual_churn_count',sum(Y));add('customers_working_MLE',Q(sum(Y),len(Y)))

rpath=ROOT/'stat18-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/'stat18-results.json').write_text(json.dumps(dict(chapter='STAT-18',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,interpretation='Original public observations are numeric inputs. Country Bernoulli likelihood, normal log-wage model and Beta customer priors are explicit working assumptions; actual iid sampling and population representativeness are not established. Likelihood is not a posterior, density is not point probability, and chosen posterior intervals do not establish frequentist coverage or future customer calibration. Public-file prefix order is not certified chronology. R independently uses dbeta/qbeta and direct log densities.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('STAT-18:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
