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

8)  Roulette "predictor" rules over 1,000,000 European spins
9)  Slot RTP convergence: how many spins before a 96% slot returns 95-97%?
10) Slot "due after a dry spell" test on 10,000,000 spins
11) No deposit bonus: GBP 10 at the 10x cap, with and without a cash-out cap
12) No deposit free spins: 50 x GBP 0.10, winnings wagered 10x
13) Tipster accuracy vs profit: zero-skill and skilled tipsters, 100 to 2,000 tips
"""
import numpy as np, json, csv, os
HERE = os.path.dirname(os.path.abspath(__file__))
rng = np.random.default_rng(20261115)
RED = {1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36}
WHEEL = [0,32,15,19,4,21,2,25,17,34,6,27,13,36,11,30,8,23,10,5,24,16,33,1,20,14,31,9,22,18,29,7,28,12,35,3,26]
POS = {n:i for i,n in enumerate(WHEEL)}
out = {}

# ---------- 8) roulette predictor rules ----------
N = 1_000_000
spins = rng.integers(0, 37, N)
W = 100
# rolling counts over the previous 100 spins
counts = np.zeros(37, int)
for s in spins[:W]: counts[s] += 1
hot_hits = cold_hits = rep_hits = sector_hits = dozen_hits = 0
colour_bets = colour_hits = 0
dozen_bets = 0
trials = 0
is_red = np.array([s in RED for s in range(37)])
for i in range(W, N):
    s = spins[i]; prev = spins[i-1]
    hot = int(np.argmax(counts)); cold = int(np.argmin(counts))
    hot_hits += (s == hot); cold_hits += (s == cold); rep_hits += (s == prev)
    p = POS[prev]; sector = {WHEEL[(p+k) % 37] for k in (-2,-1,0,1,2)}
    sector_hits += (s in sector)
    if prev != 0:
        dozen_bets += 1
        dozen_hits += (s != 0 and (s-1)//12 == (prev-1)//12)
    # opposite colour after three of the same colour
    a,b,c = spins[i-3], spins[i-2], spins[i-1]
    if a and b and c and is_red[a]==is_red[b]==is_red[c]:
        colour_bets += 1
        colour_hits += (s != 0 and is_red[s] != is_red[c])
    trials += 1
    counts[spins[i-W]] -= 1; counts[s] += 1
def row(name, hits, n, covered, pays):
    rate = hits/n; exp = covered/37
    ret = rate*(pays+1) - 1
    return dict(rule=name, bets=int(n), hit_rate_pct=round(rate*100,3), expected_pct=round(exp*100,3),
                return_per_gbp=round(ret,4))
rules = [
 row('Hot number (most hits in last 100 spins), straight up', hot_hits, trials, 1, 35),
 row('Cold or "overdue" number (fewest hits in last 100), straight up', cold_hits, trials, 1, 35),
 row('Repeat the last number, straight up', rep_hits, trials, 1, 35),
 row('Five-pocket wheel sector around the last number', sector_hits, trials, 5, 35/5 - 0.2*0 ),
 row('Same dozen as the last spin (skipped after zero)', dozen_hits, dozen_bets, 12, 2),
 row('Opposite colour after three reds or three blacks', colour_hits, colour_bets, 18, 1),
]
# sector bet: 5 straight-ups of £0.20, a hit returns 36 x 0.20 = 7.2 for 1 staked
rules[3]['return_per_gbp'] = round(sector_hits/trials*7.2 - 1, 4)
out['roulette_rules'] = dict(spins=N, lookback=W, rules=rules)
with open(os.path.join(HERE,'roulette-predictor-rules.csv'),'w',newline='') as f:
    w = csv.writer(f); w.writerow(['rule','bets','hit_rate_pct','expected_pct','return_per_gbp'])
    for r in rules: w.writerow([r['rule'], r['bets'], r['hit_rate_pct'], r['expected_pct'], r['return_per_gbp']])

# ---------- slot models (same as simulate.py) ----------
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)
SLOTS = {k: finish(*v) for k,v in MODELS.items()}

# ---------- 9) RTP convergence ----------
conv_rows = []; conv = {}
for name in ('low','medium','high'):
    pays, probs = SLOTS[name]
    conv[name] = []
    for n in (100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000):
        S = 20_000
        c = rng.multinomial(n, probs, size=S)
        rtp = (c @ pays) / n * 100
        within = float(((rtp >= 95) & (rtp <= 97)).mean()*100)
        r = dict(spins=n, sessions=S, within_95_97_pct=round(within,1), p10=round(float(np.percentile(rtp,10)),2),
                 p90=round(float(np.percentile(rtp,90)),2), above_100_pct=round(float((rtp>100).mean()*100),2))
        conv[name].append(r); conv_rows.append([name] + list(r.values()))
out['rtp_convergence'] = conv
with open(os.path.join(HERE,'slot-rtp-convergence.csv'),'w',newline='') as f:
    w = csv.writer(f); w.writerow(['model','spins','sessions','within_95_97_pct','p10_rtp','p90_rtp','above_100_pct']); w.writerows(conv_rows)

# ---------- 10) "due after a dry spell" ----------
pays, probs = SLOTS['medium']
M = 10_000_000
d = rng.choice(len(pays), size=M, p=probs)
win = pays[d] > 0
big = pays[d] >= 20
# length of losing run ending at i-1
idx = np.where(win, np.arange(M), -1)
last = np.maximum.accumulate(idx)
run = np.zeros(M, int)
run[1:] = (np.arange(M-1)) - last[:-1]   # losing spins since the last win, before spin i
after10 = run >= 10; after20 = run >= 20
after_big = np.zeros(M, bool); after_big[1:] = big[:-1]
out['slot_dry_spell'] = dict(spins=M, model='medium', base_hit_pct=round(float(win.mean()*100),2),
    hit_after_10_losses_pct=round(float(win[after10].mean()*100),2), n_after_10=int(after10.sum()),
    hit_after_20_losses_pct=round(float(win[after20].mean()*100),2), n_after_20=int(after20.sum()),
    big_win_base_pct=round(float(big.mean()*100),3), big_win_after_20_losses_pct=round(float(big[after20].mean()*100),3),
    rtp_after_20_losses_pct=round(float(pays[d][after20].mean()*100),2),
    rtp_after_big_win_pct=round(float(pays[d][after_big].mean()*100),2), n_after_big=int(after_big.sum()),
    overall_rtp_pct=round(float(pays[d].mean()*100),3))

# ---------- 11) No deposit bonus ----------
def wager_bonus(bonus, wagering_x, stake, model, S, caps):
    pays, probs = SLOTS[model]
    need = bonus*wagering_x
    spins_needed = int(round(need/stake))
    draws = rng.choice(len(pays), size=(S, spins_needed), p=probs)
    bal = bonus + np.cumsum(pays[draws]*stake - stake, axis=1)
    # bust = balance can't cover the next spin before the wagering is complete
    busted = (bal[:, :-1] < stake - 1e-9).any(axis=1)
    final = np.where(busted, 0.0, np.maximum(bal[:, -1], 0.0))
    rows = []
    for cap in caps:
        cash = np.minimum(final, cap) if cap else final
        rows.append(dict(sessions=S, bonus=bonus, wagering_x=wagering_x, wagering_gbp=need, stake=stake, spins=spins_needed,
            model=model, cap=cap, finished_pct=round(float((~busted).mean()*100),2),
            mean_cash=round(float(cash.mean()),2), median_cash=round(float(np.median(cash)),2),
            cash_ge_10_pct=round(float((cash>=10).mean()*100),2),
            hit_cap_pct=round(float((final>=cap).mean()*100),2) if cap else None,
            mean_cash_of_finishers=round(float(cash[~busted].mean()),2) if (~busted).any() else 0.0,
            p90_cash=round(float(np.percentile(cash,90)),2), best=round(float(cash.max()),2)))
    return rows
nd = []
for model in ('low','medium','high'):
    nd += wager_bonus(10, 10, 0.20, model, 100_000, (None, 100, 50))
out['no_deposit_10'] = nd
with open(os.path.join(HERE,'no-deposit-bonus-sessions.csv'),'w',newline='') as f:
    keys = list(nd[0].keys()); w = csv.writer(f); w.writerow(keys)
    for r in nd: w.writerow([r[k] for k in keys])

# ---------- 12) Free spins ----------
def free_spins(n, value, model, S, wagering_x, stake, cap=None):
    pays, probs = SLOTS[model]
    d = rng.choice(len(pays), size=(S, n), p=probs)
    won = (pays[d]*value).sum(axis=1)
    res = won.copy()
    if wagering_x:
        res = np.zeros(S)
        need_spins = np.ceil(won*wagering_x/stake - 1e-9).astype(int)
        for lo in range(0, S, 4000):
            sl = slice(lo, min(S, lo+4000)); ns = need_spins[sl]; L = int(ns.max()) if ns.size else 0
            if L == 0: continue
            dd = rng.choice(len(pays), size=(ns.size, L), p=probs)
            bal = won[sl][:,None] + np.cumsum(pays[dd]*stake - stake, axis=1)
            col = np.arange(L)[None,:]
            active = col < ns[:,None]
            prev = np.concatenate([won[sl][:,None], bal[:,:-1]], axis=1)
            bust = ((prev < stake - 1e-9) & active).any(axis=1)
            fin = bal[np.arange(ns.size), np.maximum(ns-1,0)]
            r = np.where(bust | (ns==0), 0.0, fin)
            r[ns==0] = 0.0
            res[sl] = r
    if cap: res = np.minimum(res, cap)
    return dict(spins=n, spin_value=value, model=model, sessions=S, wagering_x=wagering_x, cap=cap,
        mean_spin_winnings=round(float(won.mean()),2), zero_winnings_pct=round(float((won==0).mean()*100),2),
        mean_cash=round(float(res.mean()),2), median_cash=round(float(np.median(res)),2),
        any_cash_pct=round(float((res>=0.01).mean()*100),2))
fs = [free_spins(50, 0.10, 'medium', 20_000, 0, 0.10),
      free_spins(50, 0.10, 'medium', 20_000, 10, 0.10),
      free_spins(50, 0.10, 'medium', 20_000, 10, 0.10, cap=50)]
out['free_spins_50'] = fs

# ---------- 13) Tipster accuracy vs profit ----------
MARGIN = 1.05  # bookmaker overround assumed: implied probabilities sum to 105%
def tipster(odds, edge_yield, n_tips, S):
    # true win probability so that expected yield per GBP 1 = edge_yield
    p = (1 + edge_yield)/odds
    wins = rng.binomial(n_tips, p, size=S)
    profit = wins*odds - n_tips
    y = profit/n_tips
    return dict(odds=odds, true_p_pct=round(p*100,2), expected_yield_pct=round(edge_yield*100,2), tips=n_tips, tipsters=S,
        mean_hit_rate_pct=round(float((wins/n_tips).mean()*100),2), in_profit_pct=round(float((profit>0).mean()*100),2),
        yield_p10_pct=round(float(np.percentile(y,10)*100),1), yield_p90_pct=round(float(np.percentile(y,90)*100),1),
        best_yield_pct=round(float(y.max()*100),1))
no_skill = 1/MARGIN - 1   # -4.76%
tips = []
for odds in (1.25, 1.50, 2.00, 3.00):
    for n in (100, 500, 2000):
        tips.append(dict(kind='no_skill', **tipster(odds, no_skill, n, 100_000)))
for n in (100, 500, 2000):
    tips.append(dict(kind='skilled_plus5', **tipster(2.00, 0.05, n, 100_000)))
out['tipsters'] = dict(margin_overround=MARGIN, no_skill_yield_pct=round(no_skill*100,2), rows=tips)
# best of 1,000 zero-skill tipsters after 100 tips at 2.00 -- the "screenshot" effect
p = (1+no_skill)/2.0
best = []
for _ in range(2_000):
    w_ = rng.binomial(100, p, size=1000)
    best.append((w_.max()*2 - 100)/100)
out['tipsters']['best_of_1000_after_100_tips_mean_yield_pct'] = round(float(np.mean(best)*100),1)
# claimed-accuracy table: accuracy needed to break even, at each average price
out['tipsters']['break_even'] = [dict(odds=o, break_even_hit_pct=round(100/o,2)) for o in (1.20,1.25,1.30,1.50,1.80,2.00,2.50,3.00)]
with open(os.path.join(HERE,'tipster-accuracy-vs-profit.csv'),'w',newline='') as f:
    keys = list(tips[0].keys()); w = csv.writer(f); w.writerow(keys)
    for r in tips: w.writerow([r[k] for k in keys])

json.dump(out, open(os.path.join(HERE,'november-summary.json'),'w'), indent=1)
print(json.dumps(out, indent=1))
