"""Shared Matplotlib helpers for binary phase-diagram figures."""

from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np


STYLE_PATH = Path(__file__).with_name("plotting_style.mplstyle")


def binary_axes(
    *, xlabel="Mass fraction [-]", ylabel="T [K]", style=None, fig=None
):
    """Create a binary axis with shared formatting."""
    if style is None:
        style = STYLE_PATH

    plt.style.use(style)

    if fig is None:
        fig, ax = plt.subplots(1)
    else:
        ax = fig.add_subplot(1, 1, 1)

    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    return fig, ax


def get_style_colors():
    """Get the colors from the style"""
    plt.style.use(STYLE_PATH)

    cycle = plt.rcParams["axes.prop_cycle"]
    colors = cycle.by_key()["color"]
    return colors


# pylint: disable=too-many-arguments,too-many-positional-arguments


def binary_coords(
    weights,
    temperatures,
    *,
    order=(0, 1),
    which_idx=0,
    x_scale=1.0,
    y_scale=1.0,
):
    """Return (N, 2) array of [x, T] for binary systems."""
    w = np.asarray([np.take(v, order) for v in weights], dtype=float)
    x = w[:, which_idx] * x_scale
    y = np.asarray(temperatures, dtype=float) * y_scale
    return np.column_stack([x, y])


def plot_binary(ax, xy, **kwargs):
    """Plot a binary line from an (N, 2) array."""
    return ax.plot(xy[:, 0], xy[:, 1], **kwargs)


def scatter_binary(ax, xy, **kwargs):
    """Scatter binary points from an (N, 2) array."""
    return ax.scatter(xy[:, 0], xy[:, 1], **kwargs)
