"""Session risk numbers used in CrashSharps articles (first-session-benchmarks, tilt-recognition-protocol, five-amateur-mistakes).

Model: a crash game with 97% RTP, P(crash point >= m) = 0.97 / m for m >= 1, so 3% of rounds end at 1.00x.
Every round is independent. Exact values come from binomial formulas and dynamic programming;
a Monte Carlo run with a fixed seed cross-checks a few of them. Output: crash_session_risk_results.json.
Run: python crash_session_risk_model.py
"""
import json
import os
import random
from math import comb

RTP = 0.97
SEED = 20261016
MC_SESSIONS = 20000


def p_at_least(m):
    return RTP / m


def binom_pmf(n, k, p):
    return comb(n, k) * p ** k * (1 - p) ** (n - k)


def binom_quantiles(n, p, lo=0.025, hi=0.975):
    cdf, q_lo, q_hi = 0.0, None, None
    for k in range(n + 1):
        cdf += binom_pmf(n, k, p)
        if q_lo is None and cdf >= lo:
            q_lo = k
        if q_hi is None and cdf >= hi:
            q_hi = k
    return q_lo, q_hi


def p_loss_run(n, k, q):
    """Probability of at least one run of >= k consecutive losses in n rounds (loss probability q)."""
    dist = [1.0] + [0.0] * (k - 1)
    hit = 0.0
    for _ in range(n):
        new = [0.0] * k
        for r, pr in enumerate(dist):
            new[0] += pr * (1 - q)
            if r + 1 >= k:
                hit += pr * q
            else:
                new[r + 1] += pr * q
        dist = new
    return hit


def p_ruin_flat(units, rounds, target=2.0):
    """Flat 1-unit bets with auto-cashout at target; ruin = balance below one unit within the given rounds."""
    p_win, gain = p_at_least(target), target - 1
    # balance tracked in steps of 0.01 unit to keep the walk exact for non-integer gains
    scale = 100
    g, start = round(gain * scale), units * scale
    dist = {start: 1.0}
    ruined = 0.0
    for _ in range(rounds):
        new = {}
        for b, pr in dist.items():
            new[b + g] = new.get(b + g, 0.0) + pr * p_win
            lb = b - scale
            if lb < scale:
                ruined += pr * (1 - p_win)
            else:
                new[lb] = new.get(lb, 0.0) + pr * (1 - p_win)
        dist = new
    return ruined


def p_ruin_martingale(units, rounds, target=2.0):
    """Martingale from a 1-unit base, doubling after each loss at a 2.00x auto-cashout;
    ruin = the next bet in the progression is larger than the balance."""
    p_win = p_at_least(target)
    dist = {(units, 1): 1.0}
    ruined = 0.0
    for _ in range(rounds):
        new = {}
        for (b, bet), pr in dist.items():
            w = (b + bet, 1)
            new[w] = new.get(w, 0.0) + pr * p_win
            lb, nb = b - bet, bet * 2
            if nb > lb:
                ruined += pr * (1 - p_win)
            else:
                new[(lb, nb)] = new.get((lb, nb), 0.0) + pr * (1 - p_win)
        dist = new
    return ruined


def flat_session(rounds, target):
    """Result of a block of flat 1-unit bets at an auto-cashout target: exact distribution of P&L in units."""
    p, gain = p_at_least(target), target - 1
    pnl = {}
    for w in range(rounds + 1):
        x = round(w * gain - (rounds - w), 6)
        pnl[x] = pnl.get(x, 0.0) + binom_pmf(rounds, w, p)
    xs = sorted(pnl)
    cdf, p05 = 0.0, None
    for x in xs:
        cdf += pnl[x]
        if p05 is None and cdf >= 0.05:
            p05 = x
    return {
        "expected_pnl_units": round(sum(x * q for x, q in pnl.items()), 4),
        "p05_pnl_units": p05,
        "p_loss_more_than_10_units": round(sum(q for x, q in pnl.items() if x < -10), 4),
        "p_loss_more_than_20_units": round(sum(q for x, q in pnl.items() if x < -20), 4),
        "p_finish_in_profit": round(sum(q for x, q in pnl.items() if x > 0), 4),
    }


def crash_point(rng):
    u = rng.random()
    return 1.0 if u < 1 - RTP else RTP / (1 - u)


def monte_carlo(rng):
    """Cross-check: share of 100-round blocks with a 7+ loss run at 2.00x, and flat 10-unit ruin within 1000 rounds."""
    run7 = ruin10 = 0
    for _ in range(MC_SESSIONS):
        run = best = 0
        bal = 10
        broke = False
        for i in range(1000):
            lost = crash_point(rng) < 2.0
            if i < 100:
                run = run + 1 if lost else 0
                best = max(best, run)
            if not broke:
                bal += -1 if lost else 1
                broke = bal < 1
        run7 += best >= 7
        ruin10 += broke
    return {"sessions": MC_SESSIONS, "seed": SEED,
            "share_100_rounds_with_7plus_loss_run_2x": round(run7 / MC_SESSIONS, 4),
            "share_ruined_flat_10_units_1000_rounds_2x": round(ruin10 / MC_SESSIONS, 4)}


def labouchere_after_losses(start, k):
    """List total after k straight losses from the starting list (each loss appends the lost bet)."""
    lst = list(start)
    for _ in range(k):
        lst.append(lst[0] + lst[-1] if len(lst) > 1 else lst[0])
    return {"bets_lost": sum(lst[len(start):]), "list_total": sum(lst), "next_bet": lst[0] + lst[-1]}


def simulate_progressions(rng, players=10000, rounds=1000, bankroll=100):
    """Progressive systems from a 1-unit base at a 2.00x auto-cashout; for each player, all five systems see the same sequence of rounds.
    A player is ruined when the bet the system requires is larger than the balance; play then stops."""
    fib = [1, 1]
    while fib[-1] < 10 ** 9:
        fib.append(fib[-1] + fib[-2])

    def run(system, wins):
        bal, state = bankroll, None
        if system == "labouchere":
            state = [1, 2, 3]
        step = 0
        for i, won in enumerate(wins):
            if system == "flat":
                bet = 1
            elif system == "martingale":
                bet = 2 ** step
            elif system == "fibonacci":
                bet = fib[step]
            elif system == "dalembert":
                bet = 1 + step
            else:
                bet = state[0] + state[-1] if len(state) > 1 else state[0]
            if bet > bal:
                return bal, i
            if won:
                bal += bet
                if system == "martingale":
                    step = 0
                elif system == "fibonacci":
                    step = max(step - 2, 0)
                elif system == "dalembert":
                    step = max(step - 1, 0)
                elif system == "labouchere":
                    state = state[1:-1] or [1, 2, 3]
            else:
                bal -= bet
                if system in ("martingale", "fibonacci", "dalembert"):
                    step += 1
                elif system == "labouchere":
                    state = state + [bet]
        return bal, None

    systems = ["martingale", "fibonacci", "labouchere", "dalembert", "flat"]
    stats = {s: {"ruined": 0, "ruin_rounds": [], "final": []} for s in systems}
    p_win = p_at_least(2.0)
    for _ in range(players):
        wins = [rng.random() < p_win for _ in range(rounds)]
        for s in systems:
            bal, ruined_at = run(s, wins)
            stats[s]["final"].append(bal)
            if ruined_at is not None:
                stats[s]["ruined"] += 1
                stats[s]["ruin_rounds"].append(ruined_at)
    out = {"players": players, "rounds": rounds, "seed": SEED + 1, "bankroll_units": bankroll, "base_bet_units": 1, "cashout": 2.0}
    for s in systems:
        r = sorted(stats[s]["ruin_rounds"])
        out[s] = {
            "ruin_pct": round(100 * stats[s]["ruined"] / players, 1),
            "median_rounds_to_ruin": r[len(r) // 2] if r else None,
            "mean_final_balance_units": round(sum(stats[s]["final"]) / players, 1),
            "share_finishing_above_start_pct": round(100 * sum(b > bankroll for b in stats[s]["final"]) / players, 1),
        }
    return out


def main():
    q2 = 1 - p_at_least(2.0)
    res = {
        "model": "P(crash >= m) = 0.97 / m, m >= 1; independent rounds",
        "per_round": {
            "p_instant_1_00x": round(1 - RTP, 4),
            "p_below_2x": round(q2, 4),
            "p_shown_as_1_00x": round(1 - p_at_least(1.01), 4),
            "p_1_01_to_1_99x": round(p_at_least(1.01) - p_at_least(2.0), 4),
            "p_2x_to_9_99x": round(p_at_least(2.0) - p_at_least(10.0), 4),
            "p_10x_plus": round(p_at_least(10.0), 4),
            "p_win_at_1_50x": round(p_at_least(1.5), 4),
            "p_7_losses_in_row_at_2x": round(q2 ** 7, 5),
        },
        "shown_bracket_share": {
            "1.00-1.10x": round(1 - p_at_least(1.11), 4),
            "1.11-1.50x": round(p_at_least(1.11) - p_at_least(1.51), 4),
            "1.51-2.00x": round(p_at_least(1.51) - p_at_least(2.01), 4),
        },
        "block_100_rounds": {
            "instant_count_p0": round(binom_pmf(100, 0, 0.03), 4),
            "instant_count_p_le_6": round(sum(binom_pmf(100, k, 0.03) for k in range(7)), 4),
            "instant_count_p_ge_6": round(1 - sum(binom_pmf(100, k, 0.03) for k in range(6)), 4),
            "instant_count_95pct_range": binom_quantiles(100, 0.03),
            "below_2x_count_95pct_range": binom_quantiles(100, q2),
            "count_10x_plus_95pct_range": binom_quantiles(100, p_at_least(10.0)),
            "p_loss_run_6plus_at_2x": round(p_loss_run(100, 6, q2), 4),
            "p_loss_run_7plus_at_2x": round(p_loss_run(100, 7, q2), 4),
            "flat_1_unit_at_1_50x": flat_session(100, 1.5),
        },
        "p_loss_run_7plus_at_2x_200_rounds": round(p_loss_run(200, 7, q2), 4),
        "p_loss_run_10plus_at_2x_1000_rounds": round(p_loss_run(1000, 10, q2), 4),
        "ruin_flat_stake_at_2x": {
            f"{pct}pct_stake": {f"{n}_rounds": round(p_ruin_flat(100 // pct, n), 4) for n in (50, 100, 1000)}
            for pct in (10, 5, 2, 1)
        },
        "ruin_martingale_1pct_base_at_2x": {f"{n}_rounds": round(p_ruin_martingale(100, n), 4) for n in (100, 1000)},
        "p_more_losses_than_wins_1000_rounds_2x": round(sum(binom_pmf(1000, k, q2) for k in range(501, 1001)), 4),
        "labouchere_1_2_3_after_10_losses": labouchere_after_losses([1, 2, 3], 10),
        "monte_carlo_check": monte_carlo(random.Random(SEED)),
        "progression_systems_monte_carlo": simulate_progressions(random.Random(SEED + 1)),
    }
    out = os.path.join(os.path.dirname(os.path.abspath(__file__)), "crash_session_risk_results.json")
    with open(out, "w", encoding="utf-8", newline="\n") as f:
        json.dump(res, f, indent=2)
        f.write("\n")
    print(json.dumps(res, indent=2))


if __name__ == "__main__":
    main()
