import matplotlib.pyplot as plt
import seaborn as sns


def plot_history(
        history,
        data=[["train_loss", "valid_loss"], ["train_acc", "valid_acc"]],
        titles=["loss", "accuracy"],
        figsize=(10, 5),
        show=False,
):
    """
    Plot training history curves from a pandas DataFrame.

    This utility visualizes learning curves stored in a training history
    DataFrame, typically generated by rosoku's deep-learning pipeline.
    Each subplot corresponds to one group of metrics (e.g., loss, accuracy),
    and multiple curves (e.g., train/validation) can be overlaid per subplot.

    Internally, this function uses Seaborn line plots with ``epoch`` on the
    x-axis.

    Parameters
    ----------
    history : pandas.DataFrame
        Training history table. Must contain an ``"epoch"`` column and
        one column per metric to be plotted (e.g., ``"train_loss"``,
        ``"valid_loss"``, ``"train_acc"``, ``"valid_acc"``).

    data : list of list of str, optional
        Metric groups to plot. Each inner list defines one subplot and contains
        column names from ``history`` to be plotted together.

        Default is::

            [["train_loss", "valid_loss"],
             ["train_acc", "valid_acc"]]

    titles : list of str, optional
        Y-axis labels (and semantic titles) for each subplot.
        Must have the same length as ``data``.

        Default is ``["loss", "acc"]``.

    figsize : tuple of int, optional
        Figure size passed to :func:`matplotlib.pyplot.subplots`.

    Returns
    -------
    fig : matplotlib.figure.Figure
        The created Matplotlib figure object.

    Notes
    -----
    - This function assumes that all metric columns listed in ``data`` exist
      in ``history``. Missing columns will raise a KeyError.
    - Styling is controlled globally via :func:`seaborn.set`.
    - Axes are stacked vertically, one subplot per metric group.

    Examples
    --------
    Plot default loss and accuracy curves::

        fig = plot_history(history)

    Plot custom metrics::

        fig = plot_history(
            history,
            data=[["train_loss", "valid_loss"],
                  ["train_acc", "valid_acc"]],
            titles=["loss", "accuracy"],
        )
    """
    sns.set()

    fig, axes = plt.subplots(len(data), 1, figsize=figsize)
    for idx, _data in enumerate(data):
        for key in _data:
            sns.lineplot(data=history, x="epoch", y=key, ax=axes[idx], label=key)
            axes[idx].set_ylabel(titles[idx])

    if show:
        plt.show()

    return fig
