package mcp

import (
	"context"
	"fmt"
	"strings"

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

// WorktreeBrowseParams contains parameters for resource_worktree_browse tool
type WorktreeBrowseParams struct {
	WorktreeID string `json:"worktree_identifier" jsonschema:"required,description=Worktree branch name"`
	Path       string `json:"path,omitempty" jsonschema:"description=Path within the worktree to browse (optional)"`
}

// registerWorktreeBridgeTools registers bridge tools for worktree resources
func (s *ServerV2) registerWorktreeBridgeTools() error {
	// resource_worktree_list - Bridge to amux://worktree
	listOpts, err := WithStructOptions(
		GetEnhancedDescription("resource_worktree_list"),
		struct{}{},
	)
	if err != nil {
		return fmt.Errorf("failed to create resource_worktree_list options: %w", err)
	}
	s.mcpServer.AddTool(mcp.NewTool("resource_worktree_list", listOpts...), s.handleResourceWorktreeList)

	// resource_worktree_show - Bridge to amux://worktree/{id}
	showOpts, err := WithStructOptions(
		GetEnhancedDescription("resource_worktree_show"),
		WorktreeIDParams{},
	)
	if err != nil {
		return fmt.Errorf("failed to create resource_worktree_show options: %w", err)
	}
	s.mcpServer.AddTool(mcp.NewTool("resource_worktree_show", showOpts...), s.handleResourceWorktreeShow)

	// resource_worktree_browse - Bridge to amux://worktree/{id}/files
	// Disabled for v0.1.0: AI agents overuse it, low value for own worktree, error-prone
	// See https://github.com/choplin/amux/issues/164 for context and re-enablement considerations
	// browseOpts, err := WithStructOptions(
	// 	GetEnhancedDescription("resource_worktree_browse"),
	// 	WorktreeBrowseParams{},
	// )
	// if err != nil {
	// 	return fmt.Errorf("failed to create resource_worktree_browse options: %w", err)
	// }
	// s.mcpServer.AddTool(mcp.NewTool("resource_worktree_browse", browseOpts...), s.handleResourceWorktreeBrowse)

	return nil
}

// Bridge tool handlers for worktree resources

func (s *ServerV2) handleResourceWorktreeList(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	// Use shared logic with resource handler
	worktreeList, err := s.getWorktreeList(ctx)
	if err != nil {
		return nil, err
	}

	return createEnhancedResult("resource_worktree_list", worktreeList, nil)
}

func (s *ServerV2) handleResourceWorktreeShow(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	args := request.GetArguments()
	worktreeID, ok := args["worktree_identifier"].(string)
	if !ok || worktreeID == "" {
		return nil, fmt.Errorf("worktree_identifier is required")
	}

	// Use shared logic with resource handler
	detail, err := s.getWorktreeDetail(ctx, worktreeID)
	if err != nil {
		// Check if it's a not found error
		if strings.Contains(err.Error(), "not found") {
			return nil, WorktreeNotFoundError(worktreeID)
		}
		return nil, err
	}

	return createEnhancedResult("resource_worktree_show", detail, nil)
}

func (s *ServerV2) handleResourceWorktreeBrowse(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	args := request.GetArguments()
	worktreeID, ok := args["worktree_identifier"].(string)
	if !ok || worktreeID == "" {
		return nil, fmt.Errorf("worktree_identifier is required")
	}

	path, _ := args["path"].(string)

	// Build the URI for the resource handler
	uri := fmt.Sprintf("amux://worktree/%s/files", worktreeID)
	if path != "" {
		uri = fmt.Sprintf("%s/%s", uri, path)
	}

	// Create a resource request
	resourceReq := mcp.ReadResourceRequest{
		Params: mcp.ReadResourceParams{
			URI: uri,
		},
	}

	// Call the resource handler
	contents, err := s.handleWorktreeFilesResource(ctx, resourceReq)
	if err != nil {
		return nil, err
	}

	if len(contents) == 0 {
		return nil, fmt.Errorf("no content returned")
	}

	// Convert resource contents to tool result
	content := contents[0]
	switch c := content.(type) {
	case *mcp.TextResourceContents:
		// Create structured result for directory listings or file contents
		result := map[string]interface{}{
			"worktree_identifier": worktreeID,
			"path":                path,
			"content":             c.Text,
		}
		return createEnhancedResult("resource_worktree_browse", result, nil)
	case *mcp.BlobResourceContents:
		// For binary files, return structured result
		result := map[string]interface{}{
			"worktree_identifier": worktreeID,
			"path":                path,
			"type":                "binary",
			"mime_type":           c.MIMEType,
			"message":             fmt.Sprintf("Binary file (%s)", c.MIMEType),
		}
		return createEnhancedResult("resource_worktree_browse", result, nil)
	default:
		return nil, fmt.Errorf("unexpected content type")
	}
}
