"""STAT-05: exact finite experiments on actual source records, not case JSON.
Run beside supplied data folders. Python standard library only.
Archived Palmer/SEC originals preferred; actual CSV fallback explicitly audited.
"""
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
CHAPTER=5
ROOT=Path(__file__).resolve().parent;WORKSPACE=ROOT.parents[1]
COMMON=ROOT/'\uc2e4\uc81c\ub370\uc774\ud130';DATA=ROOT/('stats05-sources')
METRICS={};EXACT={};AUDIT=[];CHECKS={'selectedProbabilityComparisons':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 dec(value):value=Q(value);return D(value.numerator)/value.denominator
def compare(value,stored):
    assert abs(dec(value)-D(stored))<=D('1e-65')*max(D(1),abs(dec(value)))
    CHECKS['selectedProbabilityComparisons']+=1
wp=COMMON/'worldbank.csv';note(wp,'actual retained World Bank records');W=[r for r in read(wp) if r['year']=='2024'];W.sort(key=lambda r:r['country'])
country=[(Q(r['gdp_pc'])>=30000,Q(r['life_expectancy'])>=80) for r in W]
archive=WORKSPACE/'work'/'textbooks-2026'/'raw'/'penguins.csv';pp=archive if archive.is_file() else COMMON/'penguins.csv'
note(pp,'actual Palmer source records',pp==archive);P=read(pp);V=[r for r in P if r['flipper_length_mm'] not in ['','NA']]
penguins=[(r['species']=='Gentoo',Q(r['flipper_length_mm'])>=210) 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'
fallback=DATA/('actual-apple-category-sales-and-two-selection-weights.csv' if CHAPTER==4 else 'actual-apple-ten-category-year-cells-and-two-laws.csv')
S=read(fallback);note(fallback,'actual category values and selected selection-law table')
if ap.is_file():
    note(ap,'actual archived SEC category tables',True);t=Tables();t.feed(ap.read_text(encoding='utf-8'));tables=[v for v in t.tables if any(r and r[0]=='iPhone' for r in v)]
    for category in categories:
        matches=[]
        for table in tables:
            rows=[r for r in table 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:
        if CHAPTER==4:
            for year in [2023,2024]:sales[(year,r['category'])]=Q(r['reported_FY'+str(year)+'_net_sales_million_nominalUSD'])
        else:sales[(int(r['fiscal_year']),r['category'])]=Q(r['reported_net_sales_million_nominalUSD'])
x=[sales[(2023,c)] for c in categories];y=[sales[(2024,c)] for c in categories]
assert sum(x)==383285 and sum(y)==391035
order=[(True,True),(True,False),(False,True),(False,False)]
country_counts=[country.count(cell) for cell in order];penguin_counts=[penguins.count(cell) for cell in order]
assert country_counts==[8,1,0,7] and penguin_counts==[109,14,5,214]
for i,count in enumerate(country_counts,1):add('country_cell'+str(i)+'_actual_count',count)
for i,count in enumerate(penguin_counts,1):add('penguin_cell'+str(i)+'_actual_count',count)
EXPECTED={}
def event_values(atoms,weights):
    assert len(atoms)==len(weights) and sum(weights)==1
    pa=sum((w for (a,b),w in zip(atoms,weights) if a),Q(0));pb=sum((w for (a,b),w in zip(atoms,weights) if b),Q(0));ab=sum((w for (a,b),w in zip(atoms,weights) if a and b),Q(0))
    return {'P_first':pa,'P_second':pb,'P_intersection':ab,'P_union':pa+pb-ab,'P_not_first':1-pa,'P_not_second':1-pb,'P_second_given_first':ab/pa,'P_first_given_second':ab/pb,'P_first_given_not_second':(pa-ab)/(1-pb),'P_second_given_not_first':(pb-ab)/(1-pa)}
if CHAPTER==4:
    company=[(i<4,y[i]>x[i]) for i in range(5)]
    experiments={'country_uniform':(country,[Q(1,16)]*16),'penguin_uniform_valid_flipper':(penguins,[Q(1,342)]*342),'company_uniform_category':(company,[Q(1,5)]*5),'company_FY2024_sales_weighted':(company,[v/sum(y) for v in y])}
    for key,(atoms,weights) in experiments.items():
        values=event_values(atoms,weights)
        for name,value in values.items():EXPECTED[(key,name)]=value;add(key+'__'+name,value)
    tablepath=DATA/'actual-record-contingency-counts-and-assigned-probabilities.csv';T=read(tablepath);note(tablepath,'derived counts and assigned masses, not calculation inputs')
    assert len(T)==16
    for row in T:
        atoms,weights=experiments[row['experiment']];cell=(row['first_event_occurs']=='True',row['second_event_occurs']=='True')
        assert int(row['actual_record_count'])==atoms.count(cell)
        mass=sum((w for a,w in zip(atoms,weights) if a==cell),Q(0))
        assert Q(row['assigned_probability_exact'])==mass;compare(mass,row['assigned_probability_decimal'])
    calcpath=DATA/'exact-event-and-conditional-probability-calculations.csv'
else:
    def calc(group,key,value):EXPECTED[(group,key)]=value;add(group+'__'+key,value)
    pa=Q(9,16);pb=Q(1,2);ab=Q(1,2)
    for name,value in {'P_A':pa,'P_B':pb,'P_intersection':ab,'marginal_product_under_independence':pa*pb,'P_B_given_A':ab/pa,'P_A_given_B':ab/pb,'independence_gap':ab-pa*pb}.items():calc('country_uniform_actual_snapshot',name,value)
    # Directly enumerate the explicitly defined ordered ticket experiments.
    allpairs=[(i,j) for i in range(16) for j in range(16)];distinct=[(i,j) for i,j in allpairs if i!=j]
    both=lambda pairs:Q(sum(country[i][1] and country[j][1] for i,j in pairs),len(pairs))
    second=lambda pairs:Q(sum(country[j][1] for i,j in pairs),len(pairs))
    draws={'with_replacement_first_B':pb,'with_replacement_second_B':second(allpairs),'with_replacement_both_B':both(allpairs),'with_replacement_second_B_given_first_B':both(allpairs)/pb,'without_replacement_first_B':pb,'without_replacement_second_B':second(distinct),'without_replacement_both_B':both(distinct),'without_replacement_second_B_given_first_B':both(distinct)/pb}
    for name,value in draws.items():calc('country_two_ticket_selection',name,value)
    prior=Q(sum(g for g,t in penguins),len(penguins));rate_g=Q(penguin_counts[0],sum(g for g,t in penguins));rate_o=Q(penguin_counts[2],sum(not g for g,t in penguins));evidence=rate_g*prior+rate_o*(1-prior);post=rate_g*prior/evidence
    for name,value in {'P_G':prior,'P_T_given_G':rate_g,'P_T_given_other':rate_o,'P_T':evidence,'P_G_given_T':post,'P_other_given_T':1-post,'likelihood_ratio_T':rate_g/rate_o,'prior_odds_G':prior/(1-prior),'posterior_odds_G_given_T':post/(1-post)}.items():calc('penguin_original_empirical_mixture',name,value)
    grid=sorted(set([Q(1,100),Q(99,100),prior]+[Q(i,20) for i in range(1,20)]))
    path=DATA/'explicit-base-rate-reweighting-scenarios-not-new-observations.csv';T=read(path);note(path,'assumed mixture scenarios checked against independently defined22-point grid')
    assert len(T)==len(grid)==22
    for i,(p,row) in enumerate(zip(grid,T),1):
        gt=p*rate_g;gn=p*(1-rate_g);ot=(1-p)*rate_o;on=(1-p)*(1-rate_o);ev=gt+ot;po=gt/ev
        values={'prior':p,'joint_G_T':gt,'joint_G_notT':gn,'joint_other_T':ot,'joint_other_notT':on,'evidence_T':ev,'posterior_G_given_T':po}
        keys={'prior':'prior_G_exact','joint_G_T':'joint_G_T_exact','joint_G_notT':'joint_G_notT_exact','joint_other_T':'joint_other_T_exact','joint_other_notT':'joint_other_notT_exact','evidence_T':'P_T_exact','posterior_G_given_T':'posterior_G_given_T_exact'}
        for name,value in values.items():assert Q(row[keys[name]])==value;add('penguin_scenario_'+f'{i:02d}'+'_'+name,value)
        assert (row['matches_original_empirical_mixture']=='True')==(p==prior) and (row['is_assumed_reweighting_scenario']=='True')==(p!=prior)
        assert gt+gn+ot+on==1
    total=sum(x)+sum(y)
    for weighted,label in [(False,'uniform_product_choice'),(True,'sales_weighted_choice')]:
        atoms=[(i==4,year==2024) for year in [2023,2024] for i in range(5)]
        weights=[sales[(year,c)]/total if weighted else Q(1,10) for year in [2023,2024] for c in categories]
        z=event_values(atoms,weights);ps=z['P_first'];py=z['P_second'];joint=z['P_intersection']
        values={'P_S':ps,'P_Y':py,'P_S_intersection_Y':joint,'P_S_times_P_Y':ps*py,'P_S_given_Y':joint/py,'P_Y_given_S':joint/ps,'P_S_given_notY':(ps-joint)/(1-py),'independence_gap':joint-ps*py}
        for name,value in values.items():calc('company_'+label,name,value)
    calcpath=DATA/'exact-Bayes-independence-and-repeated-selection-calculations.csv'
T=read(calcpath);note(calcpath,'stored exact calculations checked, never calculation inputs')
assert len(T)==len(EXPECTED)==40
for row in T:
    value=EXPECTED[(row['experiment'],row['calculation'])]
    assert Q(row['exact_fraction'])==value and int(row['numerator'])==value.numerator and int(row['denominator'])==value.denominator
    compare(value,row['decimal_approximation'])
rpath=ROOT/'stat05-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/'stat05-results.json').write_text(json.dumps({'chapter':'STAT-05','metrics':METRICS,'exactFractions':EXACT,'inputAudit':AUDIT,'checks':CHECKS,'interpretation':'Actual records are fixed; explicit classroom selection laws and reweighting scenarios supply probabilities. These calculations do not observe customers, certify transported prediction, identify causality or turn equal marginals into independence.'},ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('STAT-05:',len(METRICS),'metrics, exact finite-law and actual-source checks passed. R comparisons:',CHECKS['RmetricComparisons'])
