"""Chapter 10 constructed exact rearrangements, bootstrap and beta updates."""
from collections import Counter
from itertools import combinations, product
from math import comb, sqrt
from statistics import mean, median, pstdev, stdev

from scipy.stats import beta
from scipy.stats import betabinom

observed=(1,2,2,3,4,5,5,10)
stats=[]
for treated in combinations(range(8),4):
    s=sum(observed[i] for i in treated)
    stats.append(s/2-8)
counts=Counter(stats)
tail=sum(abs(x)>=4 for x in stats)
print(f"Permutation: assignments={len(stats)}, observed_difference=4.000000, two_sided_tail={tail}, exact_p={tail/len(stats):.6f}")
print("Permutation distribution:", ", ".join(f"{x:g}:{counts[x]}" for x in sorted(counts)))

source=(2,3,10)
boot=list(product(source,repeat=3))
means=[mean(x) for x in boot]
medians=Counter(median(x) for x in boot)
print(f"Bootstrap: ordered_resamples={len(boot)}, mean_of_means={mean(means):.6f}, mean_SE={pstdev(means):.6f}, original_s_over_root_n={stdev(source)/sqrt(3):.6f}, median_counts={dict(sorted(medians.items()))}")

for a,b in [(1,1),(2,8),(20,80)]:
    ap,bp=a+2,b+8
    lo,hi=beta.ppf([.025,.975],ap,bp)
    print(f"Beta: prior=({a},{b}), posterior=({ap},{bp}), mean={ap/(ap+bp):.6f}, 95%_equal_tail=[{lo:.6f},{hi:.6f}], P(p>.3)={beta.sf(.3,ap,bp):.6f}")
print("Sequential stable-p update: beta(1,1) + 2/10 + 8/10 = beta(11,11)")
predictive=[betabinom.pmf(k,10,3,9) for k in range(11)]
losses=[sum((s+10*max(k-s,0))*predictive[k] for k in range(11)) for s in range(11)]
print(f"Predictive next-ten: P(K>5)={sum(predictive[6:]):.6f}, stock_loss_0_to_10={[round(float(x),6) for x in losses]}, best_stock={min(range(11),key=lambda s:losses[s])}")

assert len(stats)==comb(8,4)==70 and tail==2
assert len(boot)==27 and abs(pstdev(means)-sqrt(38/9))<1e-12
assert medians=={2:7,3:13,10:7}
assert min(range(11),key=lambda s:losses[s])==5
