import plotly.express as px


import plotly.graph_objects as go


def load_data():
    frame = px.data.gapminder()
    us = frame[frame["country"] == "United States"].sort_values("year")
    return [
        (int(year), round(float(life), 2))
        for year, life in us[["year", "lifeExp"]].itertuples(index=False, name=None)
    ]


def value_table(data):
    return {
        "columns": ["Year", "US life expectancy (years)"],
        "rows": [list(row) for row in data],
    }


def make_after(data) -> go.Figure:
    years = [row[0] for row in data]
    values = [row[1] for row in data]
    fig = go.Figure(
        go.Scatter(
            x=years,
            y=values,
            mode="lines+markers",
            line={"color": "#0072B2", "width": 2.2},
            marker={"size": 6, "color": "#0072B2"},
        )
    )
    fig.add_annotation(
        x=years[0],
        y=values[0] - 0.9,
        text="68.4 yr (1952)",
        showarrow=False,
        xanchor="left",
        font={"size": 11, "color": "#334155"},
    )
    fig.add_annotation(
        x=years[-1],
        y=values[-1] + 0.8,
        text="78.2 yr (2007)",
        showarrow=False,
        xanchor="right",
        font={"size": 11, "color": "#0072B2"},
    )
    fig.add_annotation(
        xref="paper",
        yref="paper",
        x=0,
        y=-0.22,
        text="Source: Gapminder five-year country series (1952 to 2007). Gain slowed after 1982.",
        showarrow=False,
        xanchor="left",
        font={"size": 10.5, "color": "#64748b"},
    )
    fig.update_layout(
        template="simple_white",
        title="United States life expectancy gained 9.8 years from 1952 to 2007",
        xaxis_title="Year",
        yaxis_title="Life expectancy at birth (years)",
        yaxis_range=[66, 80.5],
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        margin={"l": 64, "r": 24, "t": 48, "b": 68},
    )
    return fig


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