import os
import numpy as np
import matplotlib.pyplot as plt


def plot_cumreg_multi(curves: dict, out_path: str, title: str | None = None) -> None:
    """
    Plot mean ± SE cumulative regret for multiple algorithms.
    - Line, marker, and errorbar share the same color per algorithm.
    - Errorbars are shown at a subset of points for readability.
    """
    os.makedirs(os.path.dirname(out_path), exist_ok=True)
    plt.figure()

    markers = ["o", "s", "D", "^", "v", ">", "<", "P", "X", "*"]

    for i, (name, stats) in enumerate(curves.items()):
        mean = np.asarray(stats["mean"])
        se = np.asarray(stats["se"])
        x = np.arange(1, len(mean) + 1)

        markevery = max(1, len(x) // 12)
        eb_idx = np.arange(0, len(x), markevery)

        (line,) = plt.plot(
            x,
            mean,
            label=name,
            marker=markers[i % len(markers)],
            markevery=markevery,
            linewidth=1.8,
            markersize=4,
        )
        color = line.get_color()
        plt.errorbar(
            x[eb_idx],
            mean[eb_idx],
            yerr=se[eb_idx],
            fmt="none",
            ecolor=color,
            elinewidth=1.2,
            capsize=3,
            alpha=0.7,
        )

    plt.xlabel("Round")
    plt.ylabel("Cumulative regret")
    if title:
        plt.title(title)
    plt.legend()
    plt.tight_layout()
    plt.savefig(out_path, dpi=220)
    plt.close()
