# Lasso some points, THEN ask the chat why they stand out -- the question
# goes straight to the model via `Chat(client=...)`; a registered tool reads
# `plot.selected_rows(df)` and hands back the selected countries' own
# numbers, not a pre-digested summary, so the model has to bring its own
# knowledge of those countries to answer. The whole selection fits in the
# prompt unshrunk because 2007 gapminder only has 142 countries -- a bigger
# or unbounded selection would need a capped row count or an aggregate
# instead (see Pitfalls).
import chatlas
import plotly.express as px
from shiny import reactive
from shiny.express import ui
from shinychat.express import Chat

from shinywidgets import render_plotly

df = px.data.gapminder().query("year == 2007").reset_index(drop=True)

ui.page_opts(title="Selection as chat context", fillable=True)

with ui.layout_columns(col_widths=[7, 5]):
    with ui.card(full_screen=True):
        ui.card_header("Lasso some countries")

        @render_plotly(listen_to=["selected_rows"])
        def plot():
            fig = px.scatter(
                df, x="gdpPercap", y="lifeExp", color="continent",
                custom_data=[df.index],
            )
            return fig.update_xaxes(type="log").update_layout(dragmode="lasso")

    with ui.card(full_screen=True):
        ui.card_header("Ask about your selection")

        def get_selection() -> str:
            """The countries the user lassoed on the scatter plot, with their
            GDP per capita and life expectancy."""
            # Required here -- see Pitfalls, "Tool calls run outside the
            # reactive graph".
            with reactive.isolate():
                rows = plot.selected_rows(df)
            return rows[["country", "continent", "gdpPercap", "lifeExp"]].to_csv(
                index=False
            )

        chat_client = chatlas.ChatAnthropic(
            model="claude-haiku-5-5",
            system_prompt="You analyze a lasso selection from a gapminder scatter "
            "plot (gdp per capita vs. life expectancy, 2007). Call get_selection to "
            "see exactly which countries are selected before answering.",
        )
        chat_client.register_tool(get_selection)

        chat = Chat(
            "chat",
            client=chat_client,
            greeting="Lasso some points, then ask me about them.",
        )
        chat.ui()
