package api

import (
	"context"
	"encoding/json"
	"testing"

	"github.com/muyue/muyue/internal/agent"
)

func TestHandleToolCall(t *testing.T) {
	// Test unknown tool returns error
	registry := agent.NewRegistry()

	// Register a test tool
	testTool, _ := agent.NewTool[struct{ Command string }]("test_tool", "Test tool", func(ctx context.Context, params struct{ Command string }) (agent.ToolResponse, error) {
		return agent.TextResponse("executed: " + params.Command), nil
	})
	registry.Register(testTool)

	// Test executing known tool
	resp, err := registry.Execute(context.Background(), agent.ToolCall{
		ID:   "test-id",
		Name: "test_tool",
		Arguments: json.RawMessage(`{"Command": "hello"}`),
	})
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if resp.IsError {
		t.Errorf("expected no error, got error response")
	}

	// Test executing unknown tool
	resp, err = registry.Execute(context.Background(), agent.ToolCall{
		ID:   "test-id",
		Name: "unknown_tool",
		Arguments: json.RawMessage(`{}`),
	})
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if !resp.IsError {
		t.Errorf("expected error for unknown tool")
	}
}

func TestCleanThinkingTags(t *testing.T) {
	tests := []struct {
		input    string
		expected string
	}{
		{"hello world", "hello world"},
		{"<think>thinking</think>hello", "hello"},
		{"<Think>THINKING</Think>hello", "hello"},
		{"hello <think>thinking</think> world", "hello  world"},
		{"no tags here", "no tags here"},
	}

	for _, tc := range tests {
		result := cleanThinkingTags(tc.input)
		if result != tc.expected {
			t.Errorf("cleanThinkingTags(%q) = %q, want %q", tc.input, result, tc.expected)
		}
	}
}