package mcp

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

	"github.com/mark3labs/mcp-go/mcp"

	worktree "github.com/aki/amux/internal/worktree"
)

func TestWorktreeBridgeTools(t *testing.T) {
	testServer := setupTestServer(t)

	// Create test worktrees
	ws1Opts := worktree.CreateOptions{
		Name:        "test-worktree-1",
		Description: "First test worktree",
	}
	ws1, err := testServer.worktreeManager.Create(context.Background(), ws1Opts)
	if err != nil {
		t.Fatalf("failed to create worktree 1: %v", err)
	}

	ws2Opts := worktree.CreateOptions{
		Name:        "test-worktree-2",
		Description: "Second test worktree",
	}
	ws2, err := testServer.worktreeManager.Create(context.Background(), ws2Opts)
	if err != nil {
		t.Fatalf("failed to create worktree 2: %v", err)
	}

	t.Run("resource_worktree_list returns all worktrees", func(t *testing.T) {
		req := mcp.CallToolRequest{
			Params: mcp.CallToolParams{
				Name:      "resource_worktree_list",
				Arguments: map[string]interface{}{},
			},
		}

		result, err := testServer.handleResourceWorktreeList(context.Background(), req)
		if err != nil {
			t.Fatalf("expected no error, got %v", err)
		}

		if len(result.Content) != 1 {
			t.Fatalf("expected 1 content, got %d", len(result.Content))
		}

		textContent, ok := result.Content[0].(mcp.TextContent)
		if !ok {
			t.Fatalf("expected TextContent, got %T", result.Content[0])
		}

		// Parse enhanced result
		var enhancedResult struct {
			Result []map[string]interface{} `json:"result"`
		}
		if err := json.Unmarshal([]byte(textContent.Text), &enhancedResult); err != nil {
			t.Fatalf("failed to unmarshal response: %v", err)
		}
		worktrees := enhancedResult.Result

		if len(worktrees) != 2 {
			t.Errorf("expected 2 worktrees, got %d", len(worktrees))
		}
	})

	t.Run("resource_worktree_show returns worktree details", func(t *testing.T) {
		req := mcp.CallToolRequest{
			Params: mcp.CallToolParams{
				Name: "resource_worktree_show",
				Arguments: map[string]interface{}{
					"worktree_identifier": ws1.Branch,
				},
			},
		}

		result, err := testServer.handleResourceWorktreeShow(context.Background(), req)
		if err != nil {
			t.Fatalf("expected no error, got %v", err)
		}

		if len(result.Content) != 1 {
			t.Fatalf("expected 1 content, got %d", len(result.Content))
		}

		textContent, ok := result.Content[0].(mcp.TextContent)
		if !ok {
			t.Fatalf("expected TextContent, got %T", result.Content[0])
		}

		// Parse enhanced result
		var enhancedResult struct {
			Result map[string]interface{} `json:"result"`
		}
		if err := json.Unmarshal([]byte(textContent.Text), &enhancedResult); err != nil {
			t.Fatalf("failed to unmarshal response: %v", err)
		}
		detail := enhancedResult.Result

		if detail["id"] != ws1.Branch {
			t.Errorf("expected worktree ID %s, got %v", ws1.Branch, detail["id"])
		}
		if detail["name"] != ws1.Branch {
			t.Errorf("expected worktree name %s, got %v", ws1.Branch, detail["name"])
		}
	})

	t.Run("resource_worktree_browse lists directory contents", func(t *testing.T) {
		t.Skip("resource_worktree_browse is disabled in v0.1.0")
		req := mcp.CallToolRequest{
			Params: mcp.CallToolParams{
				Name: "resource_worktree_browse",
				Arguments: map[string]interface{}{
					"worktree_identifier": ws2.Branch,
					"path":                "",
				},
			},
		}

		result, err := testServer.handleResourceWorktreeBrowse(context.Background(), req)
		if err != nil {
			t.Fatalf("expected no error, got %v", err)
		}

		if len(result.Content) != 1 {
			t.Fatalf("expected 1 content, got %d", len(result.Content))
		}

		textContent, ok := result.Content[0].(mcp.TextContent)
		if !ok {
			t.Fatalf("expected TextContent, got %T", result.Content[0])
		}

		// Parse enhanced result - browse returns structured content
		var enhancedResult struct {
			Result map[string]interface{} `json:"result"`
		}
		if err := json.Unmarshal([]byte(textContent.Text), &enhancedResult); err != nil {
			t.Fatalf("failed to unmarshal response: %v", err)
		}

		// The content field should contain the directory listing
		content, ok := enhancedResult.Result["content"].(string)
		if !ok {
			t.Fatalf("expected content to be string, got %T", enhancedResult.Result["content"])
		}

		// Should have content that indicates it's a directory listing
		if content == "" {
			t.Error("expected non-empty content")
		}

		// The content should contain directory listing text (like from ls command)
		if !strings.Contains(content, ".") && !strings.Contains(content, "total") {
			t.Error("expected directory listing content")
		}
	})
}

func TestWorktreeBridgeToolsRegistration(t *testing.T) {
	testServer := setupTestServer(t)

	// Just verify that setupTestServer succeeds, which includes registering worktree bridge tools
	if testServer == nil {
		t.Fatal("expected server to be created with worktree bridge tools registered")
	}
}
