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) & (frame["continent"] != "Oceania")]
    points = []
    summaries = []
    for continent, group in latest.groupby("continent"):
        values = sorted(float(v) for v in group["lifeExp"].to_numpy())
        mean = float(np.mean(values))
        ci95 = float(1.96 * np.std(values, ddof=1) / np.sqrt(len(values)))
        summaries.append((str(continent), len(values), round(mean, 2), round(ci95, 2)))
        for val in values:
            points.append((str(continent), round(val, 2)))
    summaries.sort(key=lambda item: item[2])
    return {"summaries": summaries, "points": points}


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


def make_after(data) -> go.Figure:
    summaries = data["summaries"]
    order = [row[0] for row in summaries]
    rng = np.random.default_rng(42)
    fig = go.Figure()
    for idx, continent in enumerate(order):
        vals = [val for c, val in data["points"] if c == continent]
        jitter = rng.uniform(-0.18, 0.18, size=len(vals))
        fig.add_trace(
            go.Scatter(
                x=vals,
                y=[idx + offset for offset in jitter],
                mode="markers",
                name=f"{continent} countries",
                showlegend=False,
                marker={"size": 6, "color": "#94a3b8", "opacity": 0.65},
            )
        )
    fig.add_trace(
        go.Scatter(
            x=[row[2] for row in summaries],
            y=list(range(len(order))),
            mode="markers",
            name="Mean and 95% CI",
            marker={"size": 10, "color": "#0072B2"},
            error_x={
                "type": "data",
                "array": [row[3] for row in summaries],
                "visible": True,
                "color": "#0072B2",
                "thickness": 2.5,
            },
        )
    )
    fig.update_layout(
        template="simple_white",
        showlegend=False,
        title="Country life expectancy in 2007 (points and mean with 95% CI)",
        xaxis_title="Life expectancy (years, 95% CI)",
        yaxis={
            "tickmode": "array",
            "tickvals": list(range(len(order))),
            "ticktext": order,
        },
        xaxis_range=[36, 86],
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        margin={"l": 92, "r": 24, "t": 48, "b": 48},
    )
    return fig


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