from statistics import mean, stdev


import plotly.graph_objects as go


def load_data():
    """Return observed turnaround times in hours for each site."""
    return [
        ("North", 18),
        ("North", 23),
        ("North", 25),
        ("North", 29),
        ("North", 35),
        ("South", 22),
        ("South", 25),
        ("South", 27),
        ("South", 30),
        ("South", 32),
        ("West", 13),
        ("West", 20),
        ("West", 26),
        ("West", 28),
        ("West", 38),
    ]


def value_table(data):
    return {
        "columns": ["Site", "Turnaround time (hours)"],
        "rows": [list(row) for row in data],
    }


def _turnaround_figure(data, show_observations):
    groups = {}
    for site, hours in data:
        groups.setdefault(site, []).append(hours)
    center = [mean(hours) for hours in groups.values()]
    spread = [stdev(hours) for hours in groups.values()]
    fig = go.Figure()
    if show_observations:
        site_positions = {site: index for index, site in enumerate(groups)}
        fig.add_scatter(
            x=[hours for _, hours in data],
            y=[site_positions[site] - 0.19 for site, _ in data],
            mode="markers",
            marker={"color": "#687887", "size": 7, "symbol": "circle-open"},
            hovertemplate="Observed turnaround %{x} h<extra></extra>",
        )
    margins = [2.776 * sd / 5**0.5 for sd in spread] if show_observations else spread
    fig.add_scatter(
        x=center,
        y=list(range(len(groups))),
        mode="markers",
        marker={"color": "#22628a", "size": 9},
        error_x={"array": margins, "color": "#22628a", "width": 5},
        hovertemplate="Mean turnaround %{x:.1f} h<extra></extra>",
    )
    subtitle = (
        "Open dots show times. Filled dots show means and 95% intervals."
        if show_observations
        else "Site means with error bars"
    )
    fig.update_layout(
        template="simple_white",
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        title={"text": "Turnaround time by site", "subtitle": {"text": subtitle}},
        xaxis={"title": "Turnaround time (hours)", "range": [10, 40]},
        yaxis={
            "tickvals": list(range(len(groups))),
            "ticktext": list(groups),
            "range": [2.5, -0.55],
        },
        showlegend=False,
        margin={"l": 70, "r": 24, "t": 78, "b": 60},
    )
    return fig


def make_after(data) -> go.Figure:
    return _turnaround_figure(data, show_observations=True)


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