package tools

import (
	"context"
	"fmt"

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

func registerContacts(s *mcp.Server, gw *gateway.Client) {
	tool := mcp.Tool{
		Name:        "get_contacts_and_leads",
		Description: "Get contact and lead data including names, emails, companies, lead scores, AI-generated lead summaries, and contact insights. Use this to understand the customer profile, identify high-value leads, and tailor agent instructions to the target audience.",
		InputSchema: mcp.InputSchema{
			Type: "object",
			Properties: map[string]mcp.Property{
				"agent_id":       {Type: "string", Description: "Filter by agent ID"},
				"lead_score_min": {Type: "integer", Description: "Minimum lead score filter"},
				"lead_score_max": {Type: "integer", Description: "Maximum lead score filter"},
				"source":         {Type: "string", Description: "Filter by source"},
				"search":         {Type: "string", Description: "Search contacts by name, email, or company"},
				"page":           {Type: "integer", Description: "Page number for pagination"},
				"limit":          {Type: "integer", Description: "Max contacts to return (default 20, max 100)"},
			},
			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.ContactListOpts{Limit: 20}
		if v, ok := args["agent_id"].(string); ok {
			opts.AgentID = v
		}
		if d, ok := args["lead_score_min"].(float64); ok && d > 0 {
			opts.LeadScoreMin = int(d)
		}
		if d, ok := args["lead_score_max"].(float64); ok && d > 0 {
			opts.LeadScoreMax = int(d)
		}
		if v, ok := args["source"].(string); ok {
			opts.Source = v
		}
		if v, ok := args["search"].(string); ok {
			opts.Search = v
		}
		if d, ok := args["page"].(float64); ok && d > 0 {
			opts.Page = int(d)
		}
		if d, ok := args["limit"].(float64); ok && d > 0 {
			opts.Limit = int(d)
			if opts.Limit > 100 {
				opts.Limit = 100
			}
		}

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

func registerGetContact(s *mcp.Server, gw *gateway.Client) {
	tool := mcp.Tool{
		Name:        "get_contact",
		Description: "Get detailed information about a single contact — email, phone, company, lead score, AI-generated summary, and insights. Use this to deep-dive into a specific lead.",
		InputSchema: mcp.InputSchema{
			Type: "object",
			Properties: map[string]mcp.Property{
				"contact_id": {Type: "string", Description: "Contact ID"},
			},
			Required: []string{"contact_id"},
		},
	}

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

func registerGetContactConversations(s *mcp.Server, gw *gateway.Client) {
	tool := mcp.Tool{
		Name:        "get_contact_conversations",
		Description: "Get all conversations for a specific contact. Use this to see the full interaction history of a particular customer or lead.",
		InputSchema: mcp.InputSchema{
			Type: "object",
			Properties: map[string]mcp.Property{
				"contact_id": {Type: "string", Description: "Contact ID"},
			},
			Required: []string{"contact_id"},
		},
	}

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