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]
    median_gdp = float(np.median(latest["gdpPercap"].to_numpy(dtype=float)))
    picks = [
        "Ethiopia",
        "Bangladesh",
        "India",
        "China",
        "Brazil",
        "Mexico",
        "Germany",
        "Norway",
    ]
    sub = latest[latest["country"].isin(picks)]
    rows = [
        (str(country), round(float(gdp), 0), round(float(gdp) / median_gdp, 3))
        for country, gdp in sub[["country", "gdpPercap"]].itertuples(index=False, name=None)
    ]
    rows.sort(key=lambda item: item[2])
    return {"median": round(median_gdp, 0), "rows": rows}


def value_table(data):
    return {
        "columns": ["Country", "GDP per capita (USD)", "Ratio to global median"],
        "rows": [list(row) for row in data["rows"]],
    }


def make_after(data) -> go.Figure:
    rows = data["rows"]
    fig = go.Figure(
        go.Scatter(
            x=[row[2] for row in rows],
            y=[row[0] for row in rows],
            mode="markers",
            marker={"size": 10, "color": "#0072B2"},
        )
    )
    fig.add_vline(x=1.0, line_dash="dash", line_color="#64748b")
    for country, _, ratio in rows:
        fig.add_annotation(
            x=ratio,
            y=country,
            text=f"{ratio:.2f}x",
            showarrow=False,
            xanchor="left",
            xshift=8,
            font={"size": 11, "color": "#334155"},
        )
    fig.update_layout(
        template="simple_white",
        xaxis={
            "type": "log",
            "title": "GDP per capita relative to global median (log scale, 1x = median)",
            "tickvals": [0.125, 0.25, 0.5, 1, 2, 4, 8],
            "ticktext": ["0.125x", "0.25x", "0.5x", "1x", "2x", "4x", "8x"],
            "range": [-1.1, 1.15],
        },
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        margin={"l": 100, "r": 40, "t": 28, "b": 48},
    )
    return fig


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