import numpy as np


import plotly.express as px


import plotly.graph_objects as go


def load_data():
    frame = px.data.gapminder()
    latest = frame[frame["year"] == 2007]
    rows = []
    for continent, group in latest.groupby("continent"):
        values = group["lifeExp"].to_numpy(dtype=float)
        mean = float(np.mean(values))
        se = float(np.std(values, ddof=1) / np.sqrt(len(values))) if len(values) > 1 else 0.0
        ci95 = 1.96 * se
        rows.append((str(continent), len(values), round(mean, 2), round(ci95, 2)))
    rows.sort(key=lambda item: item[2])
    return rows


def value_table(data):
    return {
        "columns": ["Continent", "Countries", "Mean life expectancy (years)", "95% CI half-width"],
        "rows": [list(row) for row in data],
    }


def make_before(data) -> go.Figure:
    continents = [row[0] for row in data]
    means = [row[2] for row in data]
    half_widths = [row[3] for row in data]
    fig = go.Figure(
        go.Scatter(
            x=means,
            y=continents,
            mode="markers",
            marker={"size": 9, "color": "#0072B2"},
            error_x={"type": "data", "array": half_widths, "visible": True, "color": "#0072B2"},
        )
    )
    fig.update_layout(
        template="simple_white",
        xaxis_title="Life expectancy (years)",
        xaxis_range=[48, 86],
        margin={"l": 96, "r": 24, "t": 28, "b": 48},
    )
    return fig


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