import plotly.express as px


import plotly.graph_objects as go


def load_data():
    frame = px.data.gapminder()
    us = frame[frame["country"] == "United States"].set_index("year")["gdpPercap"]
    ca = frame[frame["country"] == "Canada"].set_index("year")["gdpPercap"]
    years = sorted(int(y) for y in us.index)
    return [
        (year, round(float(us[year]), 0), round(float(ca[year]), 0), round(float(us[year] - ca[year]), 0))
        for year in years
    ]


def value_table(data):
    return {
        "columns": ["Year", "United States (constant USD)", "Canada (constant USD)", "Gap: US minus Canada (constant USD)"],
        "rows": [list(row) for row in data],
    }


def make_after(data) -> go.Figure:
    years = [row[0] for row in data]
    gaps = [row[3] for row in data]
    fig = go.Figure(
        go.Scatter(
            x=years,
            y=gaps,
            mode="lines+markers",
            name="US minus Canada",
            line={"color": "#0072B2", "width": 2.5},
            marker={"size": 6, "color": "#0072B2"},
        )
    )
    fig.add_annotation(
        x=years[0],
        y=gaps[0] + 450,
        text=f"+{int(gaps[0]):,} USD",
        showarrow=False,
        font={"size": 11, "color": "#334155"},
    )
    fig.add_annotation(
        x=years[-1],
        y=gaps[-1] + 450,
        text=f"+{int(gaps[-1]):,} USD",
        showarrow=False,
        xanchor="right",
        font={"size": 11, "color": "#0072B2"},
    )
    fig.update_layout(
        template="simple_white",
        showlegend=False,
        xaxis_title="Year",
        yaxis_title="US minus Canada GDP per capita (constant USD)",
        yaxis_range=[0, 8200],
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        margin={"l": 68, "r": 24, "t": 28, "b": 48},
    )
    return fig


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