import plotly.graph_objects as go


def load_data():
    """Return bin limits in minutes and observed call counts."""
    return [(0, 2, 6), (2, 4, 6), (4, 8, 6), (8, 12, 4), (12, 20, 2)]


def value_table(data):
    total = sum(count for _, _, count in data)
    return {
        "columns": [
            "Lower limit (min)",
            "Upper limit (min)",
            "Calls",
            "Probability density (per min)",
        ],
        "rows": [[lo, hi, count, count / ((hi - lo) * total)] for lo, hi, count in data],
    }


def _call_duration_histogram(data, heights, yaxis_title):
    lower, upper, counts = zip(*data, strict=True)
    fig = go.Figure(
        go.Bar(
            x=[(lo + hi) / 2 for lo, hi in zip(lower, upper, strict=True)],
            width=[hi - lo for lo, hi in zip(lower, upper, strict=True)],
            y=heights,
            marker={"color": "#347a9c", "line": {"color": "#ffffff", "width": 1}},
            customdata=list(zip(lower, upper, counts, strict=True)),
            hovertemplate=(
                "%{customdata[0]} to %{customdata[1]} min<br>%{customdata[2]} calls<extra></extra>"
            ),
        )
    )
    fig.update_layout(
        template="simple_white",
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        title_text="Support call duration",
        bargap=0,
        xaxis={"title": "Duration (minutes)", "dtick": 4},
        yaxis={"title": yaxis_title, "rangemode": "tozero"},
        margin={"l": 78, "r": 24, "t": 60, "b": 62},
    )
    return fig


def make_before(data) -> go.Figure:
    return _call_duration_histogram(data, [count for _, _, count in data], "Calls")


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