"""STAT-08: 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,math
getcontext().prec=110
ROOT=Path(__file__).resolve().parent;WORKSPACE=ROOT.parents[1]
COMMON=ROOT/'\uc2e4\uc81c\ub370\uc774\ud130';DATA=ROOT/'stats08-sources'
METRICS={};EXACT={};APPROX=[];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)
    if isinstance(value,(Q,int)):EXACT[key]=str(Q(value))
    else:APPROX.append(key)
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])
def normal_cdf(z):return math.erfc(-float(z)/math.sqrt(2))/2
def normal_sf(z):return math.erfc(float(z)/math.sqrt(2))/2
def interval(a,b):return normal_sf(a)-normal_sf(b) if a>0 else normal_cdf(b)-normal_cdf(a)
def near(a,b):assert abs(float(a)-float(b))<=1e-12*max(1,abs(float(a))),(a,b);CHECKS['selectedValuesCompared']+=1
def bpmf(n,p,k):return Q(math.comb(n,k))*p**k*(1-p)**(n-k)
def poisson_positive_upper_tail(lam,cutoff):
    # Directly sum positive terms, never 1-CDF, preserving tiny-tail accuracy.
    rate=D(lam.numerator)/lam.denominator;k=cutoff+1
    term=(-rate).exp()*rate**k/D(math.factorial(k));total=term
    while True:
        k+=1;term*=rate/k;total+=term
        if term<total*D('1e-105'):return float(total)
wp=COMMON/'worldbank.csv';note(wp,'actual retained World Bank records');W=sorted([r for r in read(wp) if r['year']=='2024'],key=lambda r:r['country']);assert len(W)==16
p=Q(sum(r['country']=='SGP' for r in W),len(W));life_p=Q(sum(Q(r['life_expectancy'])>=80 for r in W),len(W));n=16;lam=n*p
path=DATA/'actual-country-events-for-chosen-replacement-experiments.csv';S=read(path);note(path,'actual country events, not observed repeated draws');assert len(S)==16
for r,s in zip(W,S):
    assert r['country']==s['country'] and (s['chosen_event_is_SGP']=='True')==(r['country']=='SGP') and (s['chosen_life_ge80_event']=='True')==(Q(r['life_expectancy'])>=80)
    same(Q(r['gdp_pc']),s['reported_GDPpc_constant2015USD_per_person']);same(Q(r['life_expectancy']),s['reported_life_expectancy_years'])
B=[bpmf(n,p,k) for k in range(n+1)];Pois=[math.exp(-float(lam))*float(lam)**k/math.factorial(k) for k in range(n+1)]
path=DATA/'chosen-country-binomial-law-and-Poisson-approximation.csv';S=read(path);note(path,'binomial exact and Poisson approximate values checked, not inputs');assert len(S)==17
for k,r in enumerate(S):
    assert k==int(r['count_k']);same(B[k],r['exact_binomial_probability']);same(sum(B[:k+1]),r['binomial_CDF_exact']);near(Pois[k],r['Poisson_approximation_probability_decimal110']);near(Pois[k]-float(B[k]),r['signed_Poisson_minus_binomial_error_decimal110']);near(sum(Pois[:k+1]),r['Poisson_CDF_approximation_decimal110'])
    add('country_binomial_k'+str(k),B[k]);add('country_Poisson_k'+str(k),Pois[k])
for key,value in {'country_actual_tickets':len(W),'country_chosen_SGP_probability':p,'country_chosen_trials':n,'country_binomial_mean':sum(Q(k)*b for k,b in enumerate(B)),'country_binomial_variance':sum((Q(k)-lam)**2*b for k,b in enumerate(B)),'country_Poisson_lambda':lam,'country_Poisson_tail_above16':poisson_positive_upper_tail(lam,16),'country_life_ge80_actual_probability':life_p,'country_two_life_draws_P0':(1-life_p)**2,'country_without_replacement_all16_count':sum(r['country']=='SGP' for r in W)}.items():add(key,value)
archive=WORKSPACE/'work'/'textbooks-2026'/'raw'/'penguins.csv';pp=archive if archive.is_file() else COMMON/'penguins.csv';note(pp,'actual Palmer mass records',pp==archive);P=read(pp);V=[r for r in P if r['body_mass_g'] not in ['','NA']];mass=[Q(r['body_mass_g']) for r in V];N=len(mass);mu=avg(mass);vv=var(mass);sd=math.sqrt(float(vv));assert len(P)==344 and N==342
path=DATA/'actual-penguin-masses-with-original-missing-records.csv';S=read(path);note(path,'all actual source masses and missing status');assert len(S)==344
for i,(r,s) in enumerate(zip(P,S),1):
    ok=r['body_mass_g'] not in ['','NA'];assert int(s['source_row_id'])==i and (s['body_mass_available']=='True')==ok and r['species']==s['species']
    if ok:same(Q(r['body_mass_g']),s['reported_body_mass_g']);same(Q(1,N),s['assigned_valid_record_probability_exact'])
    else:assert s['reported_body_mass_g']==s['assigned_valid_record_probability_exact']==''
path=DATA/'actual-mass-bin-probabilities-and-assumed-normal-integrals.csv';S=read(path);note(path,'same-interval empirical probabilities and assumed normal integrals');assert len(S)==10
for i,r in enumerate(S):
    lo=None if i==0 else 2500+500*(i-1);hi=None if i==9 else 2500+500*i
    count=sum((lo is None or v>=lo) and (hi is None or v<hi) for v in mass);prob=Q(count,N)
    np=(normal_cdf((hi-float(mu))/sd) if lo is None else normal_sf((lo-float(mu))/sd) if hi is None else interval((lo-float(mu))/sd,(hi-float(mu))/sd))
    assert int(r['actual_record_count'])==count;same(prob,r['actual_empirical_bin_probability_exact']);near(np,r['assumed_moment_matched_normal_probability_decimal110']);near(np-float(prob),r['signed_normal_minus_empirical_error_decimal110'])
    for key,value in {'actual_count':count,'empirical_probability':prob,'assumed_normal_probability':np}.items():add('penguin_bin'+str(i)+'_'+key,value)
within=Q(sum(abs(float(v-mu))<=sd for v in mass),N)
for key,value in {'penguin_original_rows':len(P),'penguin_valid_mass_records':N,'penguin_actual_mean_g':mu,'penguin_actual_variance_g2':vv,'penguin_actual_SD_g':sd,'penguin_empirical_mass3800_atom':Q(sum(v==3800 for v in mass),N),'penguin_empirical_interval3500to4000':Q(sum(3500<=v<4000 for v in mass),N),'penguin_normal_interval3500to4000':interval((3500-float(mu))/sd,(4000-float(mu))/sd),'penguin_empirical_within_one_SD':within,'penguin_assumed_normal_within_one_SD':interval(-1,1)}.items():add(key,value)
class Tables(HTMLParser):
    def __init__(self):super().__init__();self.tables=[];self.stack=[];self.row=None;self.cell=None
    def handle_starttag(self,t,a):
        if t=='table':self.stack.append([])
        elif t=='tr' and self.stack:self.row=[]
        elif t in ['td','th'] and self.row is not None:self.cell=[]
    def handle_data(self,s):
        if self.cell is not None:self.cell.append(s)
    def handle_endtag(self,t):
        if t in ['td','th'] and self.cell is not None:self.row.append(' '.join(' '.join(self.cell).split()));self.cell=None
        elif t=='tr' and self.row is not None:self.stack[-1].append(self.row);self.row=None
        elif t=='table' and self.stack:self.tables.append(self.stack.pop())
categories=['iPhone','Mac','iPad','Wearables, Home and Accessories','Services'];sales={}
ap=WORKSPACE/'work'/'textbook-rewrite-2026'/'source-audit-math08'/'apple-2024.html'
path=DATA/'actual-apple-category-pairs-and-increase-indicators.csv';S=read(path);note(path,'actual paired category values, not previous numeric results')
if ap.is_file():
    note(ap,'actual archived SEC tables',True);parser=Tables();parser.feed(ap.read_text(encoding='utf-8'));tables=[t for t in parser.tables if any(r and r[0]=='iPhone' for r in t)]
    for c in categories:
        matches=[]
        for t in tables:
            rows=[r for r in t if r and re.sub(r'\s*\(\d+\)$','',r[0])==c]
            if rows:matches.append(tuple(int(v.replace(',','')) for v in rows[0][1:] if re.fullmatch(r'\d{1,3}(?:,\d{3})+',v)))
        assert matches and len(set(matches))==1 and len(matches[0])==3
        for year,value in zip([2024,2023,2022],matches[0]):sales[(year,c)]=Q(value)
else:
    for r in S:
        for year in [2023,2024]:sales[(year,r['category'])]=Q(r['actual_FY'+str(year)+'_net_sales_million_nominalUSD'])


x=[sales[(2023,c)] for c in categories];y=[sales[(2024,c)] for c in categories];flags=[b>a for a,b in zip(x,y)];p=Q(sum(flags),len(flags));n=100;mu=n*p;vv=n*p*(1-p);sd=math.sqrt(float(vv))
assert sum(x)==383285 and sum(y)==391035 and p==Q(3,5)
for i,r in enumerate(S):
    assert r['category']==categories[i] and (r['actual_paired_increase']=='True')==flags[i]
    same(x[i],r['actual_FY2023_net_sales_million_nominalUSD']);same(y[i],r['actual_FY2024_net_sales_million_nominalUSD']);assert int(r['FY2023_weeks'])==53 and int(r['FY2024_weeks'])==52
    add('company_category'+str(i+1)+'_actual_increase',int(flags[i]))
B=[bpmf(n,p,k) for k in range(n+1)];path=DATA/'chosen-company-binomial-law-and-normal-continuity-cells.csv';S=read(path);note(path,'exact binomial masses and assumed normal continuity-cell integrals checked');assert len(S)==101
for k,r in enumerate(S):
    model=interval((k-.5-float(mu))/sd,(k+.5-float(mu))/sd)
    assert int(r['count_k'])==k;same(B[k],r['exact_binomial_probability']);near(model,r['normal_continuity_cell_probability_decimal110']);near(model-float(B[k]),r['signed_normal_minus_binomial_error_decimal110']);same(Q(2*k-1,2),r['normal_continuity_cell_lower']);same(Q(2*k+1,2),r['normal_continuity_cell_upper'])
    add('company_binomial_k'+str(k),B[k]);add('company_normal_continuity_cell_k'+str(k),model)
tail=sum(B[70:]);corrected=normal_sf((69.5-float(mu))/sd);uncorrected=normal_sf((70-float(mu))/sd)
for key,value in {'company_actual_categories':len(categories),'company_actual_increase_tickets':sum(flags),'company_chosen_success_probability':p,'company_chosen_trials':n,'company_binomial_mean':sum(Q(k)*b for k,b in enumerate(B)),'company_binomial_variance':sum((Q(k)-mu)**2*b for k,b in enumerate(B)),'company_exact_upper_tail70':tail,'company_normal_corrected_upper_tail70':corrected,'company_normal_uncorrected_upper_tail70':uncorrected,'company_normal_corrected_absolute_error':abs(corrected-float(tail)),'company_normal_uncorrected_absolute_error':abs(uncorrected-float(tail)),'company_normal_mass_outside_cells0to100':normal_cdf((-.5-float(mu))/sd)+normal_sf((100.5-float(mu))/sd)}.items():add(key,value)
assert abs(corrected-float(tail))<abs(uncorrected-float(tail))
rpath=ROOT/'stat08-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)
    tiny=[key for key,value in METRICS.items() if 0<abs(value)<1e-9]
    for key in tiny:assert abs(R[key]/METRICS[key]-1)<=1e-8,(key,R[key],METRICS[key])
    CHECKS['tinyNonzeroMetricRelativeComparisons']=len(tiny)
    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/'stat08-results.json').write_text(json.dumps({'chapter':'STAT-08','metrics':METRICS,'exactFractions':EXACT,'numericalApproximationMetrics':APPROX,'inputAudit':AUDIT,'checks':CHECKS,'interpretation':{'law':'Actual data are finite fixed inputs; independent replacement sequences and Poisson/normal laws are explicitly specified assumptions, not actual repeated observations or future forecasts.','numeric':'Fractions preserve exact finite-law arithmetic. Approximate-function metrics are separately listed, never presented as exact fractions of mathematical probabilities. Python math.erfc supplies independent binary64 normal calculations and Decimal110 sums positive Poisson upper-tail terms without subtraction; R uses pnorm/dbinom/dpois/ppois upper tails. General selected comparisons use absolute floor1e-12 and cross-runtime metrics1e-10, with an additional relative error<=1e-8 check for every nonzero metric smaller than1e-9. Tiny probabilities are not excused by the absolute floor.'}},ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('STAT-08:',len(METRICS),'metrics; actual-source exact laws and independent approximate-function checks passed. R comparisons:',CHECKS['RmetricComparisons'])
