package mcp

import (
	"context"
	"encoding/json"
	"fmt"

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

// registerResources registers all MCP resources
func (s *ServerV2) registerResources() error {
	// Register worktree list resource
	worktreeListResource := mcp.NewResource(
		"amux://worktree",
		"Worktree List",
		mcp.WithResourceDescription("List all amux worktrees"),
		mcp.WithMIMEType("application/json"),
	)
	s.mcpServer.AddResource(worktreeListResource, s.handleWorktreeListResource)

	return nil
}

// workspaceInfo is the common structure for worktree information
type workspaceInfo struct {
	ID          string `json:"id"`
	Index       string `json:"index"`
	Name        string `json:"name"`
	Branch      string `json:"branch"`
	BaseBranch  string `json:"baseBranch"`
	Description string `json:"description,omitempty"`
	StoragePath string `json:"storagePath,omitempty"`
	CreatedAt   string `json:"createdAt"`
	UpdatedAt   string `json:"updatedAt"`
	Resources   struct {
		Detail string `json:"detail"`
		Files  string `json:"files"`
	} `json:"resources"`
}

// handleWorktreeListResource returns a list of all worktrees
func (s *ServerV2) handleWorktreeListResource(ctx context.Context, request mcp.ReadResourceRequest) ([]mcp.ResourceContents, error) {
	worktreeList, err := s.getWorktreeList(ctx)
	if err != nil {
		return nil, err
	}

	jsonData, err := json.MarshalIndent(worktreeList, "", "  ")
	if err != nil {
		return nil, fmt.Errorf("failed to marshal workspace list: %w", err)
	}

	return []mcp.ResourceContents{
		&mcp.TextResourceContents{
			URI:      request.Params.URI,
			MIMEType: "application/json",
			Text:     string(jsonData),
		},
	}, nil
}
