# Lasso some points, then ask the chat about them. The get_selection tool
# hands the model the selected rows, and the model brings its own knowledge
# of those countries.
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="Ask about your selection", 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", hover_name="country",
                log_x=True, custom_data=[df.index],
            )
            return fig.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."""
            # Currently required to read reactive values from a chat tool.
            with reactive.isolate():
                rows = plot.selected_rows(df)
            return rows[["country", "continent", "gdpPercap", "lifeExp"]].to_csv(
                index=False
            )

        client = chatlas.ChatAnthropic(
            model="claude-haiku-5-5",
            system_prompt="You help explore a scatter plot of 2007 gapminder data "
            "(GDP per capita vs. life expectancy). Call get_selection to see "
            "which countries the user has lassoed.",
        )
        client.register_tool(get_selection)

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