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 math import exp, log


from random import Random


from statistics import mean, quantiles, stdev


from plotly.subplots import make_subplots


def load_data():
    rng = Random(81)
    rows = []
    for site, n in [("Harbor", 18), ("Market", 30), ("Ridge", 24)]:
        for _ in range(n):
            old = rng.uniform(12, 26)
            rows.append((site, old, old * exp(rng.gauss(-0.2, 0.12))))
    return rows


def make_after(data):
    fig = make_subplots(
        rows=1,
        cols=2,
        horizontal_spacing=0.20,
        subplot_titles=("Paired time ratios", "Geometric mean and 95% CI"),
    )
    for site in ("Harbor", "Market", "Ridge"):
        ratios = sorted(new / old for group, old, new in data if group == site)
        label = f"{site} (n={len(ratios)})"
        q1, med, q3 = quantiles(ratios, n=4, method="inclusive")
        logs = [log(v) for v in ratios]
        center = mean(logs)
        half = 1.96 * stdev(logs) / len(logs) ** 0.5
        fig.add_scatter(
            x=[min(ratios), max(ratios)],
            y=[label] * 2,
            mode="lines",
            line=dict(color=MUTED, width=1),
            row=1,
            col=1,
        )
        fig.add_scatter(
            x=[q1, med, q3],
            y=[label] * 3,
            mode="markers",
            marker=dict(
                color=INK, size=11, symbol=["line-ns", "circle", "line-ns"], line_width=1.6
            ),
            row=1,
            col=1,
        )
        estimate = exp(center)
        fig.add_scatter(
            x=[estimate],
            y=[label],
            mode="markers",
            marker_color=WARM_EDITORIAL_PALETTE[0],
            error_x=dict(
                type="data",
                symmetric=False,
                array=[exp(center + half) - estimate],
                arrayminus=[estimate - exp(center - half)],
            ),
            row=1,
            col=2,
        )
    fig.add_vline(x=1, line_color=MUTED, line_dash="dot")
    fig.update_xaxes(title_text="Revised / original", range=[0.54, 1.10], tickvals=[0.6, 0.8, 1])
    fig.update_yaxes(showticklabels=False, row=1, col=2)
    fig.update_layout(
        template="warm_editorial",
        title="Revised tasks take less time at all three sites",
        title_subtitle_text="Left: range, quartiles and median   /   Right: mean ratio with approximate 95% CI",
        margin=dict(l=115, r=25, t=100, b=50),
        showlegend=False,
    )
    return fig


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