package tui

import (
	"encoding/json"
	"strings"
	"testing"

	"github.com/patriceckhart/zot/packages/provider"
)

func TestLiveToolOverlayRemainsAfterAssistantToolUse(t *testing.T) {
	args := json.RawMessage(`{"command":"sleep 1"}`)
	v := View{
		Theme: Dark,
		Messages: []provider.Message{
			{
				Role: provider.RoleAssistant,
				Content: []provider.Content{
					provider.ToolCallBlock{ID: "toolu_1", Name: "bash", Arguments: args},
				},
			},
		},
		ToolCalls: []ToolCallView{
			{ID: "toolu_1", Name: "bash", Args: ShortArgs("bash", args), Done: false},
		},
	}

	plain := stripANSI(strings.Join(v.Build(80), "\n"))
	if !strings.Contains(plain, "bash sleep 1") {
		t.Fatalf("live tool overlay disappeared after assistant tool_use was appended:\n%s", plain)
	}
}

func TestLiveToolOverlayKeepsWritePreviewAfterArgsEnd(t *testing.T) {
	args := json.RawMessage(`{"path":"/tmp/sample.ts","content":"export const n = 1\n"}`)
	v := View{
		Theme: Dark,
		Messages: []provider.Message{
			{
				Role: provider.RoleAssistant,
				Content: []provider.Content{
					provider.ToolCallBlock{ID: "toolu_1", Name: "write", Arguments: args},
				},
			},
		},
		ToolCalls: []ToolCallView{
			{
				ID:         "toolu_1",
				Name:       "write",
				Args:       ShortArgs("write", args),
				Streaming:  false,
				RawJSONBuf: string(args),
				LivePath:   "/tmp/sample.ts",
			},
		},
	}

	plain := stripANSI(strings.Join(v.Build(80), "\n"))
	if !strings.Contains(plain, "export const n = 1") {
		t.Fatalf("write preview collapsed after tool args ended but before tool_result arrived:\n%s", plain)
	}
}

func TestLiveToolOverlayHidesAfterToolResult(t *testing.T) {
	args := json.RawMessage(`{"command":"sleep 1"}`)
	v := View{
		Theme: Dark,
		Messages: []provider.Message{
			{
				Role: provider.RoleAssistant,
				Content: []provider.Content{
					provider.ToolCallBlock{ID: "toolu_1", Name: "bash", Arguments: args},
				},
			},
			{
				Role: provider.RoleTool,
				Content: []provider.Content{
					provider.ToolResultBlock{
						CallID:  "toolu_1",
						Content: []provider.Content{provider.TextBlock{Text: "done"}},
					},
				},
			},
		},
		ToolCalls: []ToolCallView{
			{ID: "toolu_1", Name: "bash", Args: ShortArgs("bash", args), Result: "done", Done: true},
		},
	}

	plain := stripANSI(strings.Join(v.BuildLive(80), "\n"))
	if strings.Contains(plain, "bash sleep 1") {
		t.Fatalf("live tool overlay still rendered after tool_result was appended:\n%s", plain)
	}
}
