package tools

import (
	"context"
	"fmt"

	"github.com/ClareAI/astra-insight-mcp/internal/gateway"
	"github.com/ClareAI/astra-insight-mcp/internal/mcp"
)

func registerListTemplates(s *mcp.Server, gw *gateway.Client) {
	tool := mcp.Tool{
		Name:        "list_templates",
		Description: "List pre-built agent templates. Filter by category (sales, marketing, support, etc.) or type (workflow, voice). Use templates as starting points for creating new agents.",
		InputSchema: mcp.InputSchema{
			Type: "object",
			Properties: map[string]mcp.Property{
				"category": {Type: "string", Description: "Filter by category", Enum: []string{"sales", "marketing", "support", "operations", "general", "ed_tech", "health_wellness", "ecommerce", "finance", "real_estate"}},
				"type":     {Type: "string", Description: "Filter by template type", Enum: []string{"workflow", "voice"}},
				"limit":    {Type: "integer", Description: "Max templates to return"},
			},
			Required: []string{},
		},
	}

	s.RegisterTool(tool, func(ctx context.Context, args map[string]interface{}) (interface{}, error) {
		apiKey := apiKeyFromArgs(args)
		if apiKey == "" {
			return nil, fmt.Errorf("api_key is required")
		}

		opts := gateway.TemplateListOpts{}
		if v, ok := args["category"].(string); ok {
			opts.Category = v
		}
		if v, ok := args["type"].(string); ok {
			opts.Type = v
		}
		if d, ok := args["limit"].(float64); ok && d > 0 {
			opts.Limit = int(d)
		}

		return gw.ListTemplates(ctx, apiKey, opts)
	})
}

func registerListTemplateCategories(s *mcp.Server, gw *gateway.Client) {
	tool := mcp.Tool{
		Name:        "list_template_categories",
		Description: "List available template categories.",
		InputSchema: mcp.InputSchema{
			Type:       "object",
			Properties: map[string]mcp.Property{},
			Required:   []string{},
		},
	}

	s.RegisterTool(tool, func(ctx context.Context, args map[string]interface{}) (interface{}, error) {
		apiKey := apiKeyFromArgs(args)
		if apiKey == "" {
			return nil, fmt.Errorf("api_key is required")
		}
		return gw.ListTemplateCategories(ctx, apiKey)
	})
}

func registerGetTemplate(s *mcp.Server, gw *gateway.Client) {
	tool := mcp.Tool{
		Name:        "get_template",
		Description: "Get details of a specific agent template — instructions, configuration, goals, and setup. Use this to understand a template before applying it.",
		InputSchema: mcp.InputSchema{
			Type: "object",
			Properties: map[string]mcp.Property{
				"template_id": {Type: "string", Description: "Template ID"},
			},
			Required: []string{"template_id"},
		},
	}

	s.RegisterTool(tool, func(ctx context.Context, args map[string]interface{}) (interface{}, error) {
		apiKey := apiKeyFromArgs(args)
		templateID, _ := args["template_id"].(string)
		if apiKey == "" || templateID == "" {
			return nil, fmt.Errorf("api_key and template_id are required")
		}
		return gw.GetTemplate(ctx, apiKey, templateID)
	})
}
