# Example 1 plus a second tool: highlight() lets the model point things out
# on the plot itself. Try lassoing a few countries, then asking "highlight
# other countries like these".
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="Let the model highlight points", 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],
            )
            # Keep the lasso blue and don't fade the rest, so highlights stay visible.
            fig.update_traces(selected_marker_color="#636efa", unselected_marker_opacity=1)
            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
            )

        def highlight(countries: list[str]) -> str:
            """Highlight countries on the scatter plot, replacing any current
            highlight. Pass an empty list to clear it."""
            found = set(countries) & set(df["country"])
            others = "#d3d3d3" if found else "#636efa"
            plot.widget.data[0].marker.color = [
                "#ef553b" if c in found else others for c in df["country"]
            ]
            unknown = sorted(set(countries) - found)
            return f"Highlighted {len(found)} countries." + (
                f" Not in the data: {', '.join(unknown)}." if unknown else ""
            )

        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, and highlight to point out "
            "countries on the plot.",
        )
        client.register_tool(get_selection)
        client.register_tool(highlight)

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