"""Engineering-drawing chart style for the MQL5 articles (white paper, hatching, frame, title block)."""
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

INK = "#000000"
HATCHES = ["////", "....", "xxxx", "\\\\\\\\", "oo"]

plt.rcParams.update({"font.family": "DejaVu Sans", "font.style": "italic", "font.size": 10,
                     "axes.edgecolor": INK, "text.color": INK, "axes.labelcolor": INK,
                     "xtick.color": INK, "ytick.color": INK, "hatch.linewidth": 0.6})


def paper(ax, grid=True):
    """Graph-paper background for an axes."""
    ax.set_facecolor("white")
    if grid:
        ax.minorticks_on()
        ax.grid(which="major", color="#9db8c9", lw=0.6)
        ax.grid(which="minor", color="#dbe7ee", lw=0.4)
        ax.tick_params(axis="x", which="minor", bottom=False)
        ax.set_axisbelow(True)


def frame(fig, title, stamp):
    """Drawing frame, title and title block (stamp = 3 rows of (left, right)) in the bottom right."""
    fig.add_artist(Rectangle((0.012, 0.015), 0.976, 0.97, transform=fig.transFigure,
                             fill=False, ec=INK, lw=1.6))
    fig.text(0.08, 0.925, title, fontsize=12, fontweight="bold")
    x0, y0, W, H = 0.565, 0.03, 0.415, 0.13
    fig.add_artist(Rectangle((x0, y0), W, H, transform=fig.transFigure, fill=False, ec=INK, lw=1.2))
    for yy in (y0 + H / 3, y0 + 2 * H / 3):
        fig.add_artist(plt.Line2D([x0, x0 + W], [yy, yy], transform=fig.transFigure, color=INK, lw=0.6))
    fig.add_artist(plt.Line2D([x0 + 0.29, x0 + 0.29], [y0, y0 + H], transform=fig.transFigure, color=INK, lw=0.6))
    for k, (a, b) in enumerate(stamp):
        yy = y0 + H - (k + 0.5) * H / 3
        fig.text(x0 + 0.008, yy, a, va="center", fontsize=8.5)
        fig.text(x0 + 0.298, yy, b, va="center", fontsize=8.5)


def sheet(title, stamp, size=(10, 5.6)):
    """Figure with frame, title block and one graph-paper axes for a chart."""
    fig = plt.figure(figsize=size, facecolor="white")
    frame(fig, title, stamp)
    ax = fig.add_axes([0.08, 0.30, 0.89, 0.58])
    paper(ax)
    return fig, ax


def plain(size=(10, 5.6), axes=(0.08, 0.14, 0.89, 0.82)):
    """MQL5 article style (2026-10 moderator rules): no frame, no title, no title block,
    no graph paper. One axes with light horizontal grid, top/right spines hidden."""
    fig = plt.figure(figsize=size, facecolor="white")
    ax = fig.add_axes(list(axes))
    ax.set_facecolor("white")
    ax.grid(axis="y", color="#d9d9d9", lw=0.6)
    ax.set_axisbelow(True)
    for s in ("top", "right"):
        ax.spines[s].set_visible(False)
    return fig, ax


def bare_axes(ax):
    """Scheme axes: no ticks, no spines, no grid."""
    ax.set_facecolor("white")
    ax.set_xticks([]); ax.set_yticks([])
    for s in ax.spines.values():
        s.set_visible(False)


def grouped_bars(fig, ax, labels, series, names, ylabel, fmt="{:.1f}"):
    """Hatched grouped bars with values on top; legend in the free bottom-left corner."""
    import numpy as np
    x = np.arange(len(labels)); k = len(series); w = 0.8 / k
    top = max(max(s) for s in series)
    for j, (s, nm) in enumerate(zip(series, names)):
        rr = ax.bar(x - 0.4 + w * (j + 0.5), s, w, fc="white", ec=INK, lw=1.0, hatch=HATCHES[j], label=nm)
        for r in rr:
            ax.text(r.get_x() + r.get_width() / 2, r.get_height() + top * 0.015, fmt.format(r.get_height()),
                    ha="center", va="bottom", fontsize=8.5)
    ax.set_xticks(x); ax.set_xticklabels(labels, style="normal")
    ax.set_ylabel(ylabel); ax.set_ylim(0, top * 1.3)
    ax.legend(loc="upper left", ncol=len(series), frameon=False, fontsize=9.5)
