"""STAT-09: 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
from collections import Counter
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/'stats09-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 near(a,b):assert abs(float(a)-float(b))<=1e-12*max(1,abs(float(a))),(a,b);CHECKS['selectedValuesCompared']+=1
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(Q(r['life_expectancy'])>=80 for r in W),len(W));assert p==Q(1,2)
path=DATA/'actual-country-indicators-and-chosen-success-event.csv';S=read(path);note(path,'actual country indicator checks');assert len(S)==16
for r,s in zip(W,S):
    assert r['country']==s['country'] and (s['chosen_success_life_ge80']=='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'])
path=DATA/'exact-country-iid-error-probabilities-and-Chebyshev-bounds.csv';S=read(path);note(path,'exact chosen iid error probabilities and moment bounds checked');assert len(S)==5
for n,r in zip([10,20,50,100,500],S):
    pmf=[Q(math.comb(n,k))*p**k*(1-p)**(n-k) for k in range(n+1)];tail=sum((prob for k,prob in enumerate(pmf) if abs(Q(k,n)-p)>=Q(1,10)),Q(0));bound=min(Q(1),p*(1-p)/(n*Q(1,10)**2))
    assert n==int(r['chosen_iid_replacement_sample_size_n']) and r['error_event_includes_boundary']=='True' and tail<=bound
    for key,value,stored in [('tail',tail,'exact_probability_absolute_error_ge_tolerance'),('bound',bound,'Chebyshev_upper_bound_capped_at_one_exact'),('variance',p*(1-p)/n,'sample_mean_variance_exact')]:same(value,r[stored]);add('country_n'+str(n)+'_'+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);assert len(P)==344 and N==342 and all(v.denominator==1 and v%25==0 for v in mass)
path=DATA/'actual-penguin-masses-with-original-missing-records.csv';S=read(path);note(path,'actual masses and missing-row checks');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
    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']==''
freq=Counter(int(v)//25 for v in mass);dist={0:1};laws={}
for n in range(1,9):
    nxt=Counter()
    for a,ac in dist.items():
        for b,bc in freq.items():nxt[a+b]+=ac*bc
    dist=dict(nxt);assert sum(dist.values())==N**n
    if n in [1,2,4,8]:laws[n]=dist.copy()
path=DATA/'exact-penguin-iid-sample-mean-laws-by-integer-convolution.csv';S=read(path);note(path,'all exact complete sample-mean laws checked against integer convolution');assert len(S)==sum(len(v) for v in laws.values())
seen=set()
for r in S:
    n=int(r['chosen_iid_sample_size_n']);t=int(r['sum_in_25g_units']);count=laws[n][t]
    assert (n,t) not in seen;seen.add((n,t));assert count==int(r['ordered_source_record_tuples_count']) and N**n==int(r['all_ordered_record_tuples_count']) and 25*t==int(r['sum_g'])
    same(Q(25*t,n),r['sample_mean_g_exact']);same(Q(count,N**n),r['sample_mean_probability_exact'])
path=DATA/'exact-penguin-sample-mean-moments-and-reference-intervals.csv';S=read(path);note(path,'exact means, variances and within-standard-error probability checks');assert len(S)==4
for n,r in zip([1,2,4,8],S):
    law=laws[n];den=N**n;expect=sum((Q(25*t,n)*c/den for t,c in law.items()),Q(0));vari=sum(((Q(25*t,n)-mu)**2*c/den for t,c in law.items()),Q(0));within=Q(sum(c for t,c in law.items() if (Q(25*t,n)-mu)**2<=vv/n),den)
    assert expect==mu and vari==vv/n and int(r['exact_distribution_support_points'])==len(law)
    same(expect,r['sample_mean_expectation_g_exact']);same(vari,r['sample_mean_variance_g2_exact']);same(within,r['exact_probability_within_one_standard_error']);near(math.sqrt(float(vari)),r['sample_mean_SD_g_decimal110']);near(math.erf(1/math.sqrt(2)),r['normal_reference_within_one_standard_error_decimal110'])
    for key,value in {'support':len(law),'expectation':expect,'variance':vari,'SD':math.sqrt(float(vari)),'within_one_SE':within}.items():add('penguin_n'+str(n)+'_'+key,value)
def cdf(n,z):
    cutoff=z*z*vv/n;count=0
    for t,c in laws[n].items():
        delta=Q(25*t,n)-mu
        if (delta<=0 or delta*delta<=cutoff) if z>=0 else (delta<0 and delta*delta>=cutoff):count+=c
    return Q(count,N**n)
path=DATA/'exact-penguin-iid-standardized-CDF-at-specified-z.csv';S=read(path);note(path,'exact standardized CDF values, independently compared with binary64 normal reference');assert len(S)==13
for i,r in enumerate(S):
    z=Q(i-6,2);same(z,r['standardized_z_exact']);normal=math.erfc(-float(z)/math.sqrt(2))/2;near(normal,r['standard_normal_CDF_decimal110']);add('penguin_z'+str(i)+'_standard_normal_CDF',normal)
    for n in [1,2,4,8]:value=cdf(n,z);same(value,r['exact_n'+str(n)+'_standardized_CDF']);add('penguin_n'+str(n)+'_z'+str(i)+'_CDF',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-pairs-and-two-explicit-selection-weights.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)];up=Q(sum(flags),5);wp=sum((v for v,f in zip(y,flags) if f),Q(0))/sum(y);bias=wp-up
assert sum(x)==383285 and sum(y)==391035 and up==Q(3,5)
for i,r in enumerate(S):
    assert r['category']==categories[i] and (r['actual_increase_indicator']=='True')==flags[i];same(x[i],r['actual_FY2023_net_sales_million_nominalUSD']);same(y[i],r['actual_FY2024_net_sales_million_nominalUSD']);same(y[i]/sum(y),r['actual_FY2024_sales_weight_exact'])
    assert int(r['FY2023_weeks'])==53 and int(r['FY2024_weeks'])==52
path=DATA/'exact-company-iid-dependence-and-wrong-target-MSE.csv';S=read(path);note(path,'explicit iid/dependence/changed-target models checked from actual input flags');assert len(S)==6
for n,r in zip([1,5,10,20,100,1000],S):
    values={'uniform_iid_variance':up*(1-up)/n,'copied_dependent_variance':up*(1-up),'weighted_iid_variance':wp*(1-wp)/n,'weighted_target_bias':bias,'weighted_MSE_about_uniform_target':wp*(1-wp)/n+bias*bias,'copied_dependent_error_probability':Q(1)}
    keys=['uniform_iid_mean_variance_exact','fully_dependent_repeated_first_draw_mean_variance_exact','weighted_iid_mean_variance_exact','weighted_iid_bias_relative_to_uniform_target_exact','weighted_iid_MSE_relative_to_uniform_target_exact','fully_dependent_probability_abs_error_ge_one_tenth_exact']
    assert int(r['chosen_sample_size_n'])==n
    for (key,value),stored in zip(values.items(),keys):same(value,r[stored]);add('company_n'+str(n)+'_'+key,value)
for key,value in {'country_actual_tickets':len(W),'country_actual_success_tickets':sum(Q(r['life_expectancy'])>=80 for r in W),'penguin_original_rows':len(P),'penguin_valid_mass_rows':N,'penguin_original_mean_g':mu,'penguin_original_variance_g2':vv,'company_actual_categories':5,'company_uniform_probability':up,'company_actual_sales_weighted_probability':wp,'company_asymptotic_squared_target_mismatch':bias*bias}.items():add(key,value)
rpath=ROOT/'stat09-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)
    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/'stat09-results.json').write_text(json.dumps({'chapter':'STAT-09','metrics':METRICS,'exactFractions':EXACT,'numericalApproximationMetrics':APPROX,'inputAudit':AUDIT,'checks':CHECKS,'interpretation':{'law':'Actual records are finite fixed inputs. Iid replacement draws and copied/weighted countermodels are explicitly defined classroom laws, not verified original field sampling or future forecasts.','numeric':'Python integer/Fraction convolution verifies complete laws exactly. R independently convolves normalized probability vectors with binary64 arithmetic. Normal references and square roots are numeric approximations. Cross-runtime tolerance is1e-10 with absolute floor; exact Python assertions retain all source fractions.'}},ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('STAT-09:',len(METRICS),'metrics; exact convolution and actual-source condition checks passed. R comparisons:',CHECKS['RmetricComparisons'])
