"""End-to-end: an agent posts a Slack message through an installed connector."""

from __future__ import annotations

import json

import httpx


def _call(name, args):
    return json.dumps({"thought": "act", "action": name, "args": args})


def _final(text):
    return json.dumps({"thought": "done", "action": "final", "args": {"output": text}})


def _slack_handler(request: httpx.Request) -> httpx.Response:
    if request.url.path.endswith("/chat.postMessage"):
        payload = json.loads(request.content)
        assert payload["channel"] == "C123"
        return httpx.Response(200, json={"ok": True, "ts": "1700.0001", "channel": "C123"})
    return httpx.Response(404, json={"ok": False, "error": "unknown"})


def test_agent_posts_message_via_slack_connector(
    client, helpers, set_agent_responses, set_connector_http
):
    owner = helpers.bootstrap_owner(client)
    token = owner["access_token"]

    helpers.install_connector(
        client, token, type="slack", name="Team", secrets={"bot_token": "xoxb-secret"}
    )
    agent = helpers.create_agent(client, token, name="Notifier", tools=["slack.post_message"])

    set_connector_http(_slack_handler)
    set_agent_responses(
        [
            _call("slack.post_message", {"channel": "C123", "text": "Deploy finished"}),
            _final("Posted the update to Slack."),
        ]
    )

    created = helpers.run_agent(client, token, agent["id"], input="Tell the team we shipped")
    run_id = created["run"]["id"]

    run = client.get(f"/runs/{run_id}", headers=helpers.headers(token)).json()
    assert run["status"] == "succeeded"

    steps = client.get(f"/runs/{run_id}/steps", headers=helpers.headers(token)).json()
    tool_steps = [
        s for s in steps if s["type"] == "tool_call" and s["name"] == "slack.post_message"
    ]
    assert tool_steps, "agent should have called slack.post_message"
    assert tool_steps[0]["status"] == "ok"
    assert tool_steps[0]["output"]["data"]["ts"] == "1700.0001"
