import plotly.graph_objects as go


import plotly.io as pio


INK = "#1C1917"


MUTED = "#57534E"


WARM_EDITORIAL_PALETTE = [
    "#0F766E",
    "#C2410C",
    "#1D4ED8",
    "#A16207",
    "#7E22CE",
    "#475569",
    "#0369A1",
    "#1C1917",
]


CANVAS = "#FFF7ED"


RULE = "#E7DDD2"


pio.templates["warm_editorial"] = go.layout.Template(
    layout=go.Layout(
        colorway=WARM_EDITORIAL_PALETTE,
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "size": 13, "color": INK},
        title={
            "x": 0,
            "xanchor": "left",
            "font": {"family": "Georgia, 'Times New Roman', serif", "size": 18, "color": INK},
        },
        paper_bgcolor=CANVAS,
        plot_bgcolor=CANVAS,
        xaxis={
            "showgrid": False,
            "showline": True,
            "linecolor": "#A8A29E",
            "tickcolor": "#A8A29E",
            "tickfont": {"color": MUTED},
            "automargin": True,
        },
        yaxis={
            "showgrid": True,
            "gridcolor": RULE,
            "gridwidth": 1,
            "showline": False,
            "tickcolor": "#A8A29E",
            "tickfont": {"color": MUTED},
            "zeroline": False,
            "automargin": True,
        },
    )
)


from statistics import mean, stdev


def load_data():
    return [
        [14, 16, 15, 17, 14, 18, 16, 15],
        [17, 19, 18, 20, 16, 19, 18, 21],
        [18, 20, 19, 22, 18, 20, 21, 24],
        [20, 21, 22, 23, 21, 24, 23, 27],
    ]


def make_after(data):
    days = [1, 2, 3, 4]
    means = [mean(v) for v in data]
    half = [2.365 * stdev(v) / len(v) ** 0.5 for v in data]
    fig = go.Figure()
    for direction in [-1, 1]:
        fig.add_scatter(
            x=days,
            y=[m + direction * h for m, h in zip(means, half, strict=True)],
            mode="lines",
            line=dict(color=WARM_EDITORIAL_PALETTE[0], width=1),
            fill="tonexty" if direction == 1 else None,
            fillcolor="rgba(15,118,110,0.17)",
        )
    fig.add_scatter(x=days, y=means, mode="lines+markers", line_color=WARM_EDITORIAL_PALETTE[0])
    for day, values in enumerate(data, 1):
        fig.add_scatter(
            x=[day + (i - 3.5) * 0.042 for i in range(len(values))],
            y=values,
            mode="markers",
            marker=dict(size=6, symbol="circle-open", color=INK),
        )
    fig.add_hline(
        y=22,
        line_dash="dot",
        line_color=MUTED,
        annotation_text="Target 22",
        annotation_position="top left",
    )
    fig.update_layout(
        template="warm_editorial",
        title="Day four approaches the output target",
        title_subtitle_text="Dots: eight machines per day   /   Band: pointwise 95% CI for the mean",
        xaxis=dict(title="Trial day", dtick=1),
        yaxis_title="Units per hour",
        showlegend=False,
    )
    return fig


if __name__ == "__main__":
    print(make_after(load_data()).to_json())
