package promptcompiler

import (
	"context"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/tidbcloud/AgentTeam/desktop/internal/types"
)

func TestWorkflowAgentEditDeliveryRendersAuthoringContext(t *testing.T) {
	compiler := New(DefaultPolicy())
	envelope, err := compiler.CompileDeliveryEnvelope(
		context.Background(),
		EventRoutedMessageDelivery,
		"evt-workflow-agent-edit",
		CompileInput{
			AgentID: "agent-editor",
			Runtime: "codex",
			Delivery: DeliveryCompileInput{
				MessageID:      "msg-workflow-edit",
				Target:         "workflow:plan_release",
				ChannelType:    "workflow",
				ChannelName:    "plan_release",
				AuthorIdentity: types.AuthorIdentity{ActorType: "human", DisplayName: "alice"},
				Content:        "Update this step to send the release summary.",
				MessageType:    "text",
				Metadata: map[string]any{
					workflowAgentEditMetadataKey: map[string]any{
						"kind":              "request",
						"planId":            "plan_release",
						"baseDraftRevision": float64(17),
						"responderAgentId":  "agent-editor",
						"target": map[string]any{
							"kind":     "node",
							"id":       "send_summary",
							"nodeType": "agent",
						},
						"diagnostics": []any{
							map[string]any{
								"severity": "warning",
								"code":     "WF101",
								"path":     "graph.nodes[1]",
								"message":  "Agent node timeout uses the default",
								"line":     float64(17),
								"column":   float64(9),
								"nodeId":   "send_summary",
							},
						},
					},
				},
			},
		},
	)
	require.NoError(t, err)

	rendered, err := compiler.RenderRuntimeInput(context.Background(), envelope, "codex", RenderOptions{})
	require.NoError(t, err)
	prompt := ExtractStringSlot(rendered, "deliveryText")

	assert.Contains(t, prompt, "[target=workflow:plan_release")
	assert.Contains(t, prompt, "Plan: plan_release")
	assert.Contains(t, prompt, "Base draft revision: 17")
	assert.Contains(t, prompt, "Context target: node:send_summary (agent)")
	assert.Contains(t, strings.ToLower(prompt), "diagnostic")
	assert.Contains(t, prompt, "warning")
	assert.Contains(t, prompt, "WF101")
	assert.Contains(t, prompt, "graph.nodes[1]")
	assert.Contains(t, prompt, "Agent node timeout uses the default")

	for _, operation := range []string{"show", "validate", "update"} {
		assert.Contains(t, prompt, "workflow plan "+operation)
	}
	assert.Contains(t, prompt, "The target is context, not a write boundary.")
	assert.Contains(t, prompt, "Do not send an acknowledgement or progress message")
	assert.Contains(t, prompt, "the first reply ends this edit request")
}
