"""STAT-03: independently reconstruct paired moments, units and within/between terms.
Uses actual World Bank, Palmer and SEC records, not case JSON numeric values.
Python standard library, exact Fraction arithmetic and Decimal110 square roots.
"""
from pathlib import Path
from fractions import Fraction as Q
from decimal import Decimal as D, getcontext
from html.parser import HTMLParser
import csv, hashlib, json, re
getcontext().prec=110
ROOT=Path(__file__).resolve().parent;WORKSPACE=ROOT.parents[1]
COMMON=ROOT/'\uc2e4\uc81c\ub370\uc774\ud130';DATA=ROOT/'stats03-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 dec(value):
    if isinstance(value,D):return value
    value=Q(value);return D(value.numerator)/value.denominator
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):EXACT[key]=str(value)
def compare(value,stored):
    value=dec(value);assert abs(value-D(stored))<=D('1e-65')*max(D(1),abs(value)),(value,stored)
    CHECKS['selectedValuesCompared']+=1
def moment(xs,ys):
    n=len(xs);assert n==len(ys) and n>1
    ax=sum(xs)/n;ay=sum(ys)/n;dx=[x-ax for x in xs];dy=[y-ay for y in ys]
    xx=sum(x*x for x in dx);yy=sum(y*y for y in dy);xy=sum(x*y for x,y in zip(dx,dy))
    assert sum(dx)==sum(dy)==0 and xx>0 and yy>0 and xy*xy<=xx*yy
    result={'n':n,'meanX':ax,'meanY':ay,'Sxx':xx,'Syy':yy,'Sxy':xy,'varianceXddof0':xx/n,'varianceYddof0':yy/n,'covarianceDdof0':xy/n,'varianceXddof1':xx/(n-1),'varianceYddof1':yy/(n-1),'covarianceDdof1':xy/(n-1),'sdXddof0':dec(xx/n).sqrt(),'sdYddof0':dec(yy/n).sqrt(),'sdXddof1':dec(xx/(n-1)).sqrt(),'sdYddof1':dec(yy/(n-1)).sqrt(),'correlation':dec(xy)/(dec(xx)*dec(yy)).sqrt()}
    return result,dx,dy
def record(prefix,summary):
    for key,value in summary.items():add(prefix+'_'+key,value)

wp=COMMON/'worldbank.csv';note(wp,'actual World Bank records');W=read(wp)
C=sorted([r for r in W if r['year']=='2024'],key=lambda r:r['country'])
gx=[Q(r['gdp_pc']) for r in C];gy=[Q(r['life_expectancy']) for r in C]
country,cdx,cdy=moment(gx,gy);record('country',country)
inside=sum((x-country['meanX'])**2<=country['varianceXddof0'] for x in gx)
add('country_GDP_within_one_descriptive_SD_count',inside);add('country_GDP_within_one_descriptive_SD_fraction',Q(inside,len(gx)))
assert inside==9 and len(C)==16
cp=DATA/'actual-country-GDP-lifespan-indicators-and-centered-products.csv';S=read(cp);note(cp,'selected country deviations and products')
assert len(S)==len(C)
for i,(r,s) in enumerate(zip(C,S)):
    assert r['country']==s['country'] and s['inferred_individual_causal_effect']=='False'
    for value,key in [(gx[i],'reported_GDPpc_constant2015USD_per_person'),(gy[i],'reported_life_expectancy_at_birth_years'),(cdx[i],'GDPpc_minus_selected_mean'),(cdy[i],'life_minus_selected_mean'),(cdx[i]**2,'GDPpc_deviation_squared'),(cdy[i]**2,'life_deviation_squared'),(cdx[i]*cdy[i],'centered_cross_product_GDPpc_times_years')]:compare(value,s[key])

archive=WORKSPACE/'work'/'textbooks-2026'/'raw'/'penguins.csv';pp=archive if archive.is_file() else COMMON/'penguins.csv'
P=read(pp);note(pp,'actual Palmer source records',pp==archive)
available=lambda r:all(r[k] not in ['','NA'] for k in ['flipper_length_mm','body_mass_g'])
valid=[r for r in P if available(r)];px=[Q(r['flipper_length_mm']) for r in valid];py=[Q(r['body_mass_g']) for r in valid]
pooled,pdx,pdy=moment(px,py);kilogram,kdx,kdy=moment(px,[y/1000 for y in py])
record('penguin_pooled',pooled);record('penguin_mass_kg',kilogram)
assert len(P)==344 and len(valid)==342
assert kilogram['varianceYddof0']==pooled['varianceYddof0']/10**6 and kilogram['covarianceDdof0']==pooled['covarianceDdof0']/1000
assert abs(kilogram['correlation']-pooled['correlation'])<D('1e-100')
add('penguin_original_rows',len(P));add('penguin_missing_pair_rows',len(P)-len(valid))
species=sorted({r['species'] for r in P});groups={}
for s in species:
    v=[r for r in valid if r['species']==s]
    groups[s]=moment([Q(r['flipper_length_mm']) for r in v],[Q(r['body_mass_g']) for r in v])[0]
    record('penguin_'+s,groups[s])
within=Q(0);between=Q(0);decomp={}
for s in species:
    z=groups[s];weight=Q(z['n'],len(valid)); wi=weight*z['covarianceDdof0'];bt=weight*(z['meanX']-pooled['meanX'])*(z['meanY']-pooled['meanY'])
    within+=wi;between+=bt;decomp[s]=(weight,wi,bt)
assert within+between==pooled['covarianceDdof0']
add('penguin_weighted_within_covariance_mm_g',within);add('penguin_weighted_between_covariance_mm_g',between);add('penguin_sum_covariance_components_mm_g',within+between)
sp=DATA/'actual-penguin-pairs-and-centered-products-with-missing-rows.csv';S=read(sp);note(sp,'all source pairs, missing rows and centered products')
assert len(S)==344
j=0
for i,(r,s) in enumerate(zip(P,S),1):
    assert int(s['source_row_id'])==i and s['species']==r['species'] and (s['both_measurements_available']=='True')==available(r)
    if available(r):
        for value,key in [(px[j],'reported_flipper_length_mm'),(py[j],'reported_body_mass_g'),(pdx[j],'flipper_minus_pooled_mean_mm'),(pdy[j],'mass_minus_pooled_mean_g'),(pdx[j]*pdy[j],'centered_cross_product_mm_g')]:compare(value,s[key])
        j+=1
    else:assert all(s[k]=='' for k in ['reported_flipper_length_mm','reported_body_mass_g','centered_cross_product_mm_g'])
dp=DATA/'actual-penguin-species-covariance-decomposition.csv';S=read(dp);note(dp,'within/between species covariance identity')
assert len(S)==3
for r in S:
    z=groups[r['species']];weight,wi,bt=decomp[r['species']]
    assert int(r['valid_pair_count'])==z['n'] and Q(r['weight_exact_fraction'])==weight and Q(r['weighted_within_exact_fraction'])==wi and Q(r['weighted_between_exact_fraction'])==bt
    for value,key in [(z['meanX'],'mean_flipper_mm'),(z['meanY'],'mean_mass_g'),(z['covarianceDdof0'],'within_group_covariance_mm_g'),(wi,'weighted_within_covariance_mm_g'),(bt/weight,'between_group_mean_product_mm_g'),(bt,'weighted_between_covariance_mm_g'),(z['correlation'],'within_group_correlation')]:compare(value,r[key])

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'
sp=DATA/'actual-apple-paired-category-sales-and-centered-products.csv';S=read(sp);note(sp,'actual paired category values and centered products')
if ap.is_file():
    note(ap,'actual archived SEC HTML 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 category in categories:
        matches=[]
        for t in tables:
            rows=[r for r in t if r and re.sub(r'\s*\(\d+\)$','',r[0])==category]
            if rows:matches.append(tuple(int(c.replace(',','')) for c in rows[0][1:] if re.fullmatch(r'\d{1,3}(?:,\d{3})+',c)))
        assert matches and len(set(matches))==1 and len(matches[0])==3
        for year,value in zip([2024,2023,2022],matches[0]):sales[(year,category)]=Q(value)
else:
    for r in S:
        for year in [2023,2024]:sales[(year,r['category'])]=Q(r['reported_FY'+str(year)+'_net_sales_million_USD'])
x=[sales[(2023,c)] for c in categories];y=[sales[(2024,c)] for c in categories]
company,adx,ady=moment(x,y);record('company',company)
cosine=dec(sum(a*b for a,b in zip(x,y)))/(dec(sum(a*a for a in x))*dec(sum(b*b for b in y))).sqrt()
identity=sum((a-b)**2 for a,b in zip(x,y));add('company_uncentered_cosine',cosine);add('company_identity_squared_error_millionUSD2',identity)
assert cosine!=company['correlation'] and identity>0
for i,r in enumerate(S):
    assert r['category']==categories[i] and int(r['FY2023_weeks'])==53 and int(r['FY2024_weeks'])==52
    for value,key in [(x[i],'reported_FY2023_net_sales_million_USD'),(y[i],'reported_FY2024_net_sales_million_USD'),(adx[i],'FY2023_minus_category_mean'),(ady[i],'FY2024_minus_category_mean'),(adx[i]*ady[i],'centered_cross_product_millionUSD_squared'),((y[i]-x[i])**2,'squared_change_millionUSD_squared')]:compare(value,r[key])
summaries={'country_GDPpc_life2024':country,'penguins_pooled_flipper_mass':pooled,'penguins_mass_converted_to_kg':kilogram,'apple_FY2023_FY2024_category_sales':company,**{'penguins_'+s:groups[s] for s in species}}
sp=DATA/'descriptive-ddof0-and-ddof1-moments-and-units.csv';S=read(sp);note(sp,'display moments checked against independent calculation')
assert len(S)==7
for r in S:
    z=summaries[r['case']];assert int(r['valid_paired_n'])==z['n'] and r['ddof1_is_automatically_unbiased_claim']=='False'
    for key in z:
        if key!='n':compare(z[key],r[key])
    assert Q(r['variance0_exact_fraction'])==z['varianceXddof0'] and Q(r['varianceY0_exact_fraction'])==z['varianceYddof0'] and Q(r['covariance0_exact_fraction'])==z['covarianceDdof0']
example=moment([Q(-1),Q(0),Q(1)],[Q(1),Q(0),Q(1)])[0]
assert example['correlation']==0;add('assumed_nonlinear_example_Pearson_r',example['correlation'])
# A constant variable has an undefined correlation, recorded as metadata, not NaN/zero.
rpath=ROOT/'stat03-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 entry in AUDIT:
    path=ROOT/entry['file']
    if not path.is_file():path=WORKSPACE/entry['file']
    assert hashlib.sha256(path.read_bytes()).hexdigest()==entry['sha256']
CHECKS['inputHashesPreserved']=len(AUDIT)
(ROOT/'stat03-results.json').write_text(json.dumps({'chapter':'STAT-03','metrics':METRICS,'exactFractions':EXACT,'inputAudit':AUDIT,'checks':CHECKS,'interpretation':{'constantVariablePearson':'undefined; not replaced with numeric zero','groupMixing':'All actual group correlations are positive; no sign-reversal Simpson claim.','samplingConvention':'ddof0 describes these retained sets; ddof1 inference needs a separately justified sampling model.','scope':'Association, unit conversion and arithmetic decomposition do not identify causal effects or guarantee prediction.'}},ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('STAT-03:',len(METRICS),'metrics; paired moments, unit transformations and covariance decomposition passed. R comparisons:',CHECKS['RmetricComparisons'])
