package mcp

import (
	"context"
	"fmt"

	worktree "github.com/aki/amux/internal/worktree"
	"github.com/mark3labs/mcp-go/mcp"
)

// Bridge tools provide tool-based access to MCP resources
// for clients that don't support native resource reading.
// These tools return the same data as their resource counterparts.

// promptInfo contains basic prompt information
type promptInfo struct {
	Name        string `json:"name"`
	Description string `json:"description"`
}

// registerBridgeTools registers all bridge tools that provide access to resources
func (s *ServerV2) registerBridgeTools() error {
	// Register worktree bridge tools
	if err := s.registerWorktreeBridgeTools(); err != nil {
		return fmt.Errorf("failed to register worktree bridge tools: %w", err)
	}

	// Register prompt bridge tools
	if err := s.registerPromptBridgeTools(); err != nil {
		return fmt.Errorf("failed to register prompt bridge tools: %w", err)
	}

	return nil
}

// Shared logic for getting worktree list
func (s *ServerV2) getWorktreeList(ctx context.Context) ([]workspaceInfo, error) {
	worktrees, err := s.worktreeManager.List(ctx, worktree.ListOptions{})
	if err != nil {
		return nil, fmt.Errorf("failed to list worktrees: %w", err)
	}

	worktreeList := make([]workspaceInfo, len(worktrees))
	for i, ws := range worktrees {
		info := workspaceInfo{
			ID:          ws.Branch,
			Index:       "",
			Name:        ws.Branch,
			Branch:      ws.Branch,
			BaseBranch:  ws.BaseBranch,
			Description: ws.Description,
			StoragePath: "",
			CreatedAt:   ws.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
			UpdatedAt:   ws.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"),
		}
		info.Resources.Detail = fmt.Sprintf("amux://worktree/%s", ws.Branch)
		info.Resources.Files = fmt.Sprintf("amux://worktree/%s/files", ws.Branch)
		worktreeList[i] = info
	}

	return worktreeList, nil
}

// Shared logic for getting worktree details
func (s *ServerV2) getWorktreeDetail(ctx context.Context, worktreeID string) (*workspaceDetail, error) {
	ws, err := s.worktreeManager.ResolveWorktree(ctx, worktree.Identifier(worktreeID))
	if err != nil {
		return nil, fmt.Errorf("failed to get worktree: %w", err)
	}

	detail := &workspaceDetail{
		ID:          ws.Branch,
		Index:       "",
		Name:        ws.Branch,
		Branch:      ws.Branch,
		BaseBranch:  ws.BaseBranch,
		Description: ws.Description,
		Path:        ws.Path,
		CreatedAt:   ws.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
		UpdatedAt:   ws.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"),
	}

	// Add paths
	detail.Paths.Worktree = ws.Path

	// Add resource URIs
	detail.Resources.Files = fmt.Sprintf("amux://worktree/%s/files", ws.Branch)

	return detail, nil
}

// getRegisteredPrompts returns the list of registered prompts
func (s *ServerV2) getRegisteredPrompts() []mcp.Prompt {
	// Hard-coded list of our registered prompts
	// In the future, we might want to store these when registering
	return []mcp.Prompt{
		{
			Name:        "start-issue-work",
			Description: "Guide through starting work on a GitHub issue. Helps AI agents properly understand requirements before starting implementation",
			Arguments: []mcp.PromptArgument{
				{
					Name:        "issue_number",
					Description: "GitHub issue number to work on",
					Required:    true,
				},
				{
					Name:        "issue_title",
					Description: "Title of the GitHub issue",
					Required:    false,
				},
				{
					Name:        "issue_url",
					Description: "Full URL to the GitHub issue",
					Required:    false,
				},
			},
		},
		{
			Name:        "prepare-pr",
			Description: "Guide through preparing a pull request. Helps ensure all tests pass and code is properly formatted before creating a PR",
			Arguments: []mcp.PromptArgument{
				{
					Name:        "worktree_identifier",
					Description: "Worktree branch name to prepare PR from",
					Required:    true,
				},
				{
					Name:        "pr_title",
					Description: "Proposed PR title",
					Required:    false,
				},
				{
					Name:        "pr_description",
					Description: "Proposed PR description",
					Required:    false,
				},
			},
		},
		{
			Name:        "review-worktree",
			Description: "Analyze worktree state and suggest next steps. Helps AI agents understand what work remains to be done",
			Arguments: []mcp.PromptArgument{
				{
					Name:        "worktree_identifier",
					Description: "Worktree branch name to review",
					Required:    true,
				},
			},
		},
	}
}

// Shared logic for getting prompt list
func (s *ServerV2) getPromptList() ([]promptInfo, error) {
	// Get registered prompts
	prompts := s.getRegisteredPrompts()

	promptList := make([]promptInfo, 0, len(prompts))
	for _, prompt := range prompts {
		promptList = append(promptList, promptInfo{
			Name:        prompt.Name,
			Description: prompt.Description,
		})
	}

	return promptList, nil
}

// Shared logic for getting prompt detail
func (s *ServerV2) getPromptDetail(name string) (map[string]interface{}, error) {
	// Get registered prompts
	prompts := s.getRegisteredPrompts()

	for _, prompt := range prompts {
		if prompt.Name == name {
			detail := map[string]interface{}{
				"name":        prompt.Name,
				"description": prompt.Description,
			}

			// Add arguments if any
			if len(prompt.Arguments) > 0 {
				detail["arguments"] = prompt.Arguments
			}

			return detail, nil
		}
	}

	return nil, fmt.Errorf("prompt not found: %s", name)
}
