import numpy as np


import plotly.express as px


import plotly.graph_objects as go


def load_data():
    bills = np.sort(px.data.tips()["total_bill"].to_numpy(dtype=float))
    quantiles = np.linspace(0.025, 0.975, 20)
    dots = [round(float(np.quantile(bills, q)), 2) for q in quantiles]
    return {"bills": [round(float(v), 2) for v in bills], "dots": dots}


def value_table(data):
    return {
        "columns": ["Quantile index (1 to 20)", "Representative bill (USD)"],
        "rows": [[idx + 1, val] for idx, val in enumerate(data["dots"])],
    }


def make_before(data) -> go.Figure:
    bills = np.array(data["bills"], dtype=float)
    grid = np.linspace(0.0, 52.0, 200)
    bw = 3.2
    density = np.mean(
        np.exp(-0.5 * ((grid[:, None] - bills[None, :]) / bw) ** 2)
        + np.exp(-0.5 * ((grid[:, None] + bills[None, :]) / bw) ** 2),
        axis=1,
    ) / (bw * np.sqrt(2 * np.pi))
    fig = go.Figure(
        go.Scatter(
            x=grid,
            y=density,
            mode="lines",
            fill="tozeroy",
            line={"color": "#0072B2", "width": 2},
            fillcolor="rgba(0, 114, 178, 0.35)",
        )
    )
    fig.add_vline(x=30, line_dash="dash", line_color="#64748b")
    fig.update_layout(
        template="simple_white",
        xaxis_title="Restaurant bill (USD)",
        yaxis_title="Probability density",
        margin={"l": 64, "r": 24, "t": 28, "b": 48},
    )
    return fig


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