import itertools


import plotly.graph_objects as go


def load_data():
    """Return successive fill volumes in milliliters."""
    return [
        467,
        472,
        479,
        481,
        484,
        488,
        491,
        494,
        497,
        499,
        502,
        504,
        506,
        509,
        512,
        515,
        520,
        526,
        531,
        537,
    ]


def value_table(data):
    return {
        "columns": ["Bottle", "Fill volume (mL)"],
        "rows": [[index, volume] for index, volume in enumerate(data, start=1)],
    }


def _fill_volume_histogram(data, width, gap):
    edges = range(460, 541, width)
    bins = list(itertools.pairwise(edges))
    fig = go.Figure(
        go.Bar(
            x=[(lo + hi) / 2 for lo, hi in bins],
            y=[sum(lo <= volume < hi for volume in data) for lo, hi in bins],
            width=width * (1 - gap),
            marker={"color": "#347a9c", "line": {"color": "#ffffff", "width": 1}},
            customdata=bins,
            hovertemplate="%{customdata[0]} to %{customdata[1]} mL<br>%{y} bottles<extra></extra>",
        )
    )
    fig.update_layout(
        template="simple_white",
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        title_text="Bottle fill volumes",
        bargap=0,
        xaxis={"title": "Fill volume (mL)", "range": [460, 540], "dtick": 20},
        yaxis={"title": "Bottles", "range": [0, 9], "dtick": 2},
        margin={"l": 60, "r": 24, "t": 60, "b": 60},
    )
    return fig


def make_before(data) -> go.Figure:
    return _fill_volume_histogram(data, width=4, gap=0.45)


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