"""STAT-07: 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
getcontext().prec=110
ROOT=Path(__file__).resolve().parent;WORKSPACE=ROOT.parents[1]
COMMON=ROOT/'\uc2e4\uc81c\ub370\uc774\ud130';DATA=ROOT/'stats07-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})
def add(key,value):METRICS[key]=float(value);EXACT[key]=str(Q(value))
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 cov(x,y):return avg([(a-avg(x))*(b-avg(y)) for a,b in zip(x,y)])
def dec(v):v=Q(v);return D(v.numerator)/v.denominator
def groups(values,labels):
    result={};total=avg(values);n=len(values)
    for label in sorted(set(labels)):
        a=[x for x,l in zip(values,labels) if l==label];w=Q(len(a),n);mu=avg(a);vv=var(a)
        result[label]={'n':Q(len(a)),'weight':w,'mean':mu,'variance':vv,'weightedMean':w*mu,'withinTerm':w*vv,'betweenTerm':w*(mu-total)**2}
    assert sum((r['weightedMean'] for r in result.values()),Q(0))==total
    assert sum((r['withinTerm']+r['betweenTerm'] for r in result.values()),Q(0))==var(values)
    return result
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']);gdp=[Q(r['gdp_pc']) for r in W];pop=[Q(r['population']) for r in W]
clabel=['life_ge_80' if Q(r['life_expectancy'])>=80 else 'life_lt_80' for r in W];CG=groups(gdp,clabel)
archive=WORKSPACE/'work'/'textbooks-2026'/'raw'/'penguins.csv';pp=archive if archive.is_file() else COMMON/'penguins.csv';note(pp,'actual Palmer source measurements',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];flipper=[Q(r['flipper_length_mm']) for r in V];PG=groups(mass,[r['species'] for r in V])
assert len(W)==16 and len(P)==344 and len(V)==342
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-paired-category-values-and-change.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];change=[b-a for a,b in zip(x,y)];AG=groups(y,['hardware']*4+['services'])
assert sum(x)==383285 and sum(y)==391035
for i,(c,r) in enumerate(zip(categories,S)):
    assert r['category']==c
    same(x[i],r['actual_FY2023_net_sales_million_nominalUSD']);same(y[i],r['actual_FY2024_net_sales_million_nominalUSD']);same(change[i],r['paired_change_million_nominalUSD']);same(Q(1,5),r['assigned_same_category_probability_exact']);same(y[i]/sum(y),r['FY2024_actual_sales_weight_probability_exact'])
    same(AG[r['group']]['mean'],r['FY2024_conditional_group_mean_exact'])
    assert int(r['FY2023_weeks'])==53 and int(r['FY2024_weeks'])==52
path=DATA/'actual-country-values-and-conditional-mean-map.csv';C=read(path);note(path,'actual country values and conditional map checks');assert len(C)==16
for r,s,value,label in zip(W,C,gdp,clabel):
    assert r['country']==s['country'] and s['life_group']==label
    for value_,key in [(value,'reported_GDPpc_constant2015USD_per_person'),(Q(r['life_expectancy']),'reported_life_expectancy_years'),(Q(r['population']),'reported_population_persons'),(Q(1,16),'uniform_country_probability_exact'),(CG[label]['mean'],'conditional_GDP_mean_exact'),(avg(gdp),'overall_GDP_mean_exact'),(value-CG[label]['mean'],'GDP_minus_conditional_mean_exact'),(CG[label]['mean']-avg(gdp),'conditional_mean_minus_overall_mean_exact'),(Q(r['population'])/sum(pop),'population_weight_exact')]:same(value_,s[key])
path=DATA/'actual-penguin-masses-and-species-conditional-mean-map.csv';C=read(path);note(path,'all actual penguin masses, missing rows and conditional map');assert len(C)==344
for i,(r,s) in enumerate(zip(P,C),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:
        value=Q(r['body_mass_g']);mu=PG[r['species']]['mean']
        for value_,key in [(value,'reported_body_mass_g'),(Q(r['flipper_length_mm']),'reported_flipper_length_mm'),(Q(1,342),'assigned_probability_exact'),(mu,'species_conditional_mean_g_exact'),(value-mu,'mass_minus_species_mean_g_exact'),(value-avg(mass),'mass_minus_overall_mean_g_exact')]:same(value_,s[key])
    else:assert s['reported_body_mass_g']==s['assigned_probability_exact']==s['species_conditional_mean_g_exact']==''
allgroups={'country':CG,'person':PG,'company':AG};path=DATA/'exact-conditional-moments-and-total-variance-contributions.csv';C=read(path);note(path,'conditional moments checked against newly recomputed groups');assert len(C)==7
groupkeys={'actual_valid_records':'n','assigned_group_probability_exact':'weight','conditional_mean_exact':'mean','conditional_variance_exact':'variance','weighted_mean_contribution_exact':'weightedMean','within_variance_contribution_exact':'withinTerm','between_variance_contribution_exact':'betweenTerm'}
for r in C:
    z=allgroups[r['case']][r['group']]
    for stored,key in groupkeys.items():same(z[key],r[stored]);add(r['case']+'_'+r['group']+'_'+key,z[key])
expected={}
def metric(case,name,value):expected[(case,name)]=value;add(case+'_'+name,value)
for case,values,G in [('country',gdp,CG),('person',mass,PG),('company',y,AG)]:
    metric(case,'expectation',avg(values));metric(case,'second_moment',avg([v*v for v in values]));metric(case,'variance',var(values));metric(case,'expected_conditional_variance',sum((z['withinTerm'] for z in G.values()),Q(0)));metric(case,'variance_of_conditional_expectation',sum((z['betweenTerm'] for z in G.values()),Q(0)))
metric('country','population_weighted_expectation',sum((v*w for v,w in zip(gdp,pop)),Q(0))/sum(pop))
metric('person','unweighted_three_species_means',avg([z['mean'] for z in PG.values()]));metric('person','expectation_mass_kg',avg(mass)/1000);metric('person','variance_mass_kg',var(mass)/1000000)
metric('person','expectation_flipper',avg(flipper));metric('person','expectation_flipper_times_mass',avg([l*m for l,m in zip(flipper,mass)]));metric('person','product_of_expectations',avg(flipper)*avg(mass));metric('person','covariance_flipper_mass',cov(flipper,mass))
for name,value in {'expectation_FY2023':avg(x),'expectation_FY2024':avg(y),'expectation_paired_change':avg(change),'variance_FY2023':var(x),'variance_FY2024':var(y),'covariance_two_years':cov(x,y),'variance_paired_change':var(change),'incorrect_independence_reference_variance':var(x)+var(y),'FY2024_sales_weighted_expectation':sum(v*v for v in y)/sum(y)}.items():metric('company',name,value)
assert avg(change)==avg(y)-avg(x)==1550 and var(change)==var(x)+var(y)-2*cov(x,y)==Q('23940885.2')
assert cov(flipper,mass)==avg([l*m for l,m in zip(flipper,mass)])-avg(flipper)*avg(mass)
path=DATA/'exact-law-moments-linearity-and-covariance-identities.csv';C=read(path);note(path,'stored moment identities checked, not numeric calculation inputs');assert len(C)==len(expected)==32
for r in C:
    value=expected[(r['case'],r['quantity'])];same(value,r['exact_fraction']);assert abs(dec(value)-D(r['decimal80']))<=D('1e-65')*max(D(1),abs(dec(value)))
for key,value in {'country_actual_records':len(W),'penguin_original_rows':len(P),'penguin_valid_mass_records':len(V),'company_actual_categories':len(categories),'company_total_FY2023':sum(x),'company_total_FY2024':sum(y),'company_total_actual_change':sum(change),'penguin_independent_column_ordered_pairs':len(V)**2}.items():add(key,value)
rpath=ROOT/'stat07-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/'stat07-results.json').write_text(json.dumps({'chapter':'STAT-07','metrics':METRICS,'exactFractions':EXACT,'inputAudit':AUDIT,'checks':CHECKS,'interpretation':'Moments belong to explicit finite laws over actual fixed observations. Original pairing, nonuniform group sizes, units and missingness retained. Exact conditional identities do not imply causal effects, future revenue risk or validated biological-population prediction.'},ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('STAT-07:',len(METRICS),'numeric metrics; exact actual-data moments checked. R comparisons:',CHECKS['RmetricComparisons'])
