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{})
	})
}

func registerCreateContact(s *mcp.Server, gw *gateway.Client) {
	s.RegisterTool(mcp.Tool{
		Name:        "create_contact",
		Description: "Create a new contact/lead.",
		InputSchema: mcp.InputSchema{
			Type: "object",
			Properties: map[string]mcp.Property{
				"api_key":          {Type: "string", Description: "API key"},
				"agent_id":         {Type: "string", Description: "Agent UUID to associate the contact with"},
				"conversation_id":  {Type: "string", Description: "Conversation UUID"},
				"interaction_type": {Type: "string", Description: "Interaction type: text or voice"},
				"mode":             {Type: "string", Description: "Mode: chat or voice"},
				"email":            {Type: "string", Description: "Contact email"},
				"first_name":       {Type: "string", Description: "First name"},
				"last_name":        {Type: "string", Description: "Last name"},
				"phone":            {Type: "string", Description: "Phone number"},
				"company":          {Type: "string", Description: "Company name"},
				"source":           {Type: "string", Description: "Contact source (web_widget, whatsapp, voice, api)"},
			},
			Required: []string{"agent_id", "conversation_id", "interaction_type", "mode"},
		},
	}, func(ctx context.Context, args map[string]interface{}) (interface{}, error) {
		apiKey := apiKeyFromArgs(args)
		if apiKey == "" {
			return nil, fmt.Errorf("api_key is required")
		}
		req := gateway.ContactCreateRequest{
			AgentID:         strval(args, "agent_id"),
			ConversationID:  strval(args, "conversation_id"),
			InteractionType: strval(args, "interaction_type"),
			Mode:            strval(args, "mode"),
			Email:           strval(args, "email"),
			FirstName:       strval(args, "first_name"),
			LastName:        strval(args, "last_name"),
			Phone:           strval(args, "phone"),
			Company:         strval(args, "company"),
			Source:          strval(args, "source"),
		}
		return gw.CreateContact(ctx, apiKey, req)
	})
}

func registerDeleteContact(s *mcp.Server, gw *gateway.Client) {
	s.RegisterTool(mcp.Tool{
		Name:        "delete_contact",
		Description: "Delete a contact by ID.",
		InputSchema: mcp.InputSchema{
			Type: "object",
			Properties: map[string]mcp.Property{
				"api_key":    {Type: "string", Description: "API key"},
				"contact_id": {Type: "string", Description: "Contact UUID"},
			},
			Required: []string{"contact_id"},
		},
	}, 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.DeleteContact(ctx, apiKey, contactID)
	})
}

func registerExportContacts(s *mcp.Server, gw *gateway.Client) {
	s.RegisterTool(mcp.Tool{
		Name:        "export_contacts",
		Description: "Export contacts as CSV for an agent. Returns CSV text.",
		InputSchema: mcp.InputSchema{
			Type: "object",
			Properties: map[string]mcp.Property{
				"api_key":    {Type: "string", Description: "API key"},
				"agent_id":   {Type: "string", Description: "Agent UUID (required)"},
				"start_time": {Type: "string", Description: "Filter start time (RFC 3339)"},
				"end_time":   {Type: "string", Description: "Filter end time (RFC 3339)"},
			},
			Required: []string{"agent_id"},
		},
	}, func(ctx context.Context, args map[string]interface{}) (interface{}, error) {
		apiKey := apiKeyFromArgs(args)
		agentID, _ := args["agent_id"].(string)
		if apiKey == "" || agentID == "" {
			return nil, fmt.Errorf("api_key and agent_id are required")
		}
		startTime := strval(args, "start_time")
		endTime := strval(args, "end_time")
		csvData, err := gw.ExportContacts(ctx, apiKey, agentID, startTime, endTime)
		if err != nil {
			return nil, err
		}
		return string(csvData), nil
	})
}
