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,
        },
    )
)


import numpy as np


def load_data():
    rng = np.random.default_rng(16)
    return [
        (route, old, list(rng.normal(old - saving, 2, 30)))
        for route, old, saving in zip(
            ("Bay", "Elm", "Hill", "Lake", "Mill", "Park"),
            (15, 18, 21, 24, 27, 30),
            (1, 3, 2, 5, 4, 6),
            strict=True,
        )
    ]


def make_after(data):
    fig = go.Figure()
    xs = [x for _, x, _ in data]
    ys = [float(np.mean(y)) for _, _, y in data]
    fig.add_shape(type="line", x0=12, y0=12, x1=32, y1=32, line=dict(color=MUTED, dash="dot"))
    fig.add_shape(type="line", x0=14, y0=12, x1=32, y1=30, line=dict(color=MUTED, dash="dash"))
    for probability, width, color in [(0.95, 2, MUTED), (0.5, 6, WARM_EDITORIAL_PALETTE[0])]:
        from statistics import NormalDist

        critical = NormalDist().inv_cdf((1 + probability) / 2)
        widths = [critical * float(np.std(v, ddof=1)) / len(v) ** 0.5 for _, _, v in data]
        fig.add_scatter(
            x=xs,
            y=ys,
            mode="markers",
            marker=dict(size=6, color=INK),
            error_y=dict(array=widths, thickness=width, color=color, width=3),
        )
    fig.add_scatter(
        x=xs,
        y=[32.5] * len(xs),
        mode="markers",
        marker=dict(symbol="line-ns", size=8, line_width=1, color=MUTED),
    )
    fig.add_scatter(
        x=[32.5] * len(ys),
        y=ys,
        mode="markers",
        marker=dict(symbol="line-ew", size=8, line_width=1, color=MUTED),
    )
    for i in [3, 5]:
        fig.add_annotation(x=xs[i], y=ys[i], text=data[i][0], ax=24, ay=-18)
    fig.update_layout(
        template="warm_editorial",
        title="Trial routes finish ahead of schedule",
        title_subtitle_text="Dotted: on time   /   Dashed: 2 min early   /   Mean CI: thick 50%, thin 95%",
        xaxis=dict(title="Scheduled minutes", range=[11, 34], constrain="domain"),
        yaxis=dict(title="Mean trial minutes", range=[11, 34], scaleanchor="x"),
        showlegend=False,
    )
    return fig


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