"""
ai-casino.online simulations, 23 November 2026.
Reproducible: run `python3 fairness_sims.py` (needs numpy). Fixed seed 20261123.
Writes CSV files next to this script and fairness-summary.json.

14) Could a player tell a fair 96% slot from a "rigged" 86% one by playing it?
15) How often an honest 96% slot produces sessions that feel rigged
16) Pot odds: exact draw equity by outs, and the break-even equity for each bet size
    (worked out exactly, no simulation), checked against a Monte Carlo run

The model slots are the same three used in simulate.py and november_sims.py.
The "rigged" version keeps every prize and probability except the top prize,
whose chance is cut until the return falls to 86%.
"""
import numpy as np, json, csv, os
from math import comb
HERE = os.path.dirname(os.path.abspath(__file__))
rng = np.random.default_rng(20261123)
out = {}

MODELS = {
 'low':    ([0, 0.5, 1, 2, 5, 20],          [0.52, 0.18, 0.15, 0.10, 0.04, None]),
 'medium': ([0, 0.5, 2, 5, 20, 100],        [0.70, 0.12, 0.08, 0.04, 0.015, None]),
 'high':   ([0, 1, 3, 10, 100, 1000],       [0.80, 0.10, 0.06, 0.02, 0.002, None]),
}
def finish(pays, probs, rtp=0.96):
    known = sum(p*q for p,q in zip(pays[:-1], probs[:-1]))
    last = (rtp - known)/pays[-1]
    probs = probs[:-1] + [last]
    probs[0] = 1 - sum(probs[1:])
    return np.array(pays, float), np.array(probs)

# ---------- 14) fair 96% vs rigged 86% ----------
S = 50_000
rows = []
detect = {}
for model in ('medium', 'high'):
    fp, fq = finish(*MODELS[model], rtp=0.96)
    rp, rq = finish(*MODELS[model], rtp=0.86)
    assert abs(fp @ fq - 0.96) < 1e-12 and abs(rp @ rq - 0.86) < 1e-12
    for n in (200, 1_000, 10_000, 100_000, 1_000_000):
        fair = (rng.multinomial(n, fq, size=S) @ fp) / n * 100
        rig = (rng.multinomial(n, rq, size=S) @ rp) / n * 100
        med_fair = float(np.median(fair))
        # best single cut-off for "this was the rigged slot" with a 50/50 prior
        cuts = np.linspace(min(fair.min(), rig.min()), max(fair.max(), rig.max()), 2001)
        fs = np.sort(fair); rs = np.sort(rig)
        acc = 0.5*(1 - np.searchsorted(fs, cuts, 'left')/S) + 0.5*(np.searchsorted(rs, cuts, 'left')/S)
        best = float(acc.max())
        r = dict(model=model, spins=n, sessions_each=S,
                 rigged_beats_fair_median_pct=round(float((rig > med_fair).mean()*100), 1),
                 fair_returns_under_86_pct=round(float((fair < 86).mean()*100), 1),
                 rigged_returns_over_96_pct=round(float((rig > 96).mean()*100), 1),
                 best_guess_accuracy_pct=round(best*100, 1),
                 fair_median_return_pct=round(med_fair, 1),
                 rigged_median_return_pct=round(float(np.median(rig)), 1))
        rows.append(r)
out['fair_vs_rigged'] = rows
with open(os.path.join(HERE, 'fair-vs-rigged-slot.csv'), 'w', newline='') as f:
    w = csv.writer(f); w.writerow(list(rows[0].keys()))
    for r in rows: w.writerow(list(r.values()))

# ---------- 15) "feels rigged" events on an honest 96% slot ----------
S2 = 100_000; N = 200
feel = []
for model in ('low', 'medium', 'high'):
    pays, probs = finish(*MODELS[model])
    d = rng.choice(len(pays), size=(S2, N), p=probs)
    pay = pays[d]
    win = pay > 0
    # longest run of non-winning spins in each session
    longest = np.zeros(S2, int); cur = np.zeros(S2, int)
    for j in range(N):
        cur = np.where(win[:, j], 0, cur + 1)
        longest = np.maximum(longest, cur)
    ret = pay.sum(axis=1)          # total paid back on GBP 200 staked
    big = (pay >= 20).any(axis=1)
    feel.append(dict(model=model, sessions=S2, spins=N, stake_gbp=1,
        median_longest_losing_run=int(np.median(longest)),
        losing_run_15_plus_pct=round(float((longest >= 15).mean()*100), 1),
        losing_run_25_plus_pct=round(float((longest >= 25).mean()*100), 1),
        no_20x_win_pct=round(float((~big).mean()*100), 1),
        lost_over_half_pct=round(float((ret < 100).mean()*100), 1),
        returned_under_80_pct=round(float((ret < 160).mean()*100), 1),
        mean_return_pct=round(float(ret.mean()/N*100), 2)))
out['feels_rigged'] = feel
with open(os.path.join(HERE, 'feels-rigged-sessions.csv'), 'w', newline='') as f:
    w = csv.writer(f); w.writerow(list(feel[0].keys()))
    for r in feel: w.writerow(list(r.values()))

# ---------- 16) pot odds and outs, exact ----------
def turn_only(o):  return o/47
def river_only(o): return o/46
def turn_and_river(o): return 1 - comb(47-o, 2)/comb(47, 2)
outs_rows = []
for o in range(1, 21):
    outs_rows.append(dict(outs=o,
        flop_to_turn_pct=round(turn_only(o)*100, 2),
        turn_to_river_pct=round(river_only(o)*100, 2),
        flop_to_river_pct=round(turn_and_river(o)*100, 2),
        rule_of_2_pct=2*o, rule_of_4_pct=4*o,
        rule_of_4_error_pts=round(4*o - turn_and_river(o)*100, 2)))
out['outs_equity'] = outs_rows
with open(os.path.join(HERE, 'outs-equity-exact.csv'), 'w', newline='') as f:
    w = csv.writer(f); w.writerow(list(outs_rows[0].keys()))
    for r in outs_rows: w.writerow(list(r.values()))

bet_rows = []
for frac, label in ((0.25, '1/4 pot'), (1/3, '1/3 pot'), (0.5, '1/2 pot'), (2/3, '2/3 pot'), (0.75, '3/4 pot'),
                    (1.0, 'pot'), (1.5, '1.5x pot'), (2.0, '2x pot')):
    need = frac/(1 + 2*frac)
    bet_rows.append(dict(bet=label, bet_fraction=round(frac, 4),
        pot_odds=f"{(1+frac)/frac:.2f} to 1", breakeven_equity_pct=round(need*100, 2),
        min_defence_freq_pct=round(1/(1+frac)*100, 2),
        bluff_must_work_pct=round(frac/(1+frac)*100, 2)))
out['bet_size_table'] = bet_rows
with open(os.path.join(HERE, 'pot-odds-by-bet-size.csv'), 'w', newline='') as f:
    w = csv.writer(f); w.writerow(list(bet_rows[0].keys()))
    for r in bet_rows: w.writerow(list(r.values()))

# Monte Carlo check of the exact figures: a nine-out flush draw on the flop,
# two cards to come, 2,000,000 deals from the 47 unseen cards.
M = 2_000_000
# cards 0..8 are the outs; two different cards are dealt without replacement
a = rng.integers(0, 47, M); b = rng.integers(0, 46, M); b = b + (b >= a)
hit = (a < 9) | (b < 9)
out['flush_draw_check'] = dict(deals=M, outs=9, simulated_pct=round(float(hit.mean()*100), 3),
                               exact_pct=round(turn_and_river(9)*100, 3))

# Worked call: GBP 20 pot, GBP 10 bet, nine outs with one card to come
pot, bet, o = 20, 10, 9
eq = river_only(o)
ev_call = eq*(pot+bet) - (1-eq)*bet
out['worked_call'] = dict(pot=pot, bet=bet, outs=o, equity_pct=round(eq*100, 2),
    breakeven_pct=round(bet/(pot+2*bet)*100, 2), ev_per_call_gbp=round(ev_call, 2),
    ev_per_100_calls_gbp=round(ev_call*100, 0))

with open(os.path.join(HERE, 'fairness-summary.json'), 'w') as f:
    json.dump(out, f, indent=1)
print(json.dumps(out, indent=1))
