package tools

import (
	"context"
	"fmt"

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

func registerListAnnotations(s *mcp.Server, gw *gateway.Client) {
	tool := mcp.Tool{
		Name:        "list_annotations",
		Description: "List FAQ annotations (predefined Q&A pairs) for the agent. Annotations override the LLM when matched, ensuring consistent answers. Shows questions, answers, and hit counts. Use this to see what FAQs exist and their effectiveness.",
		InputSchema: mcp.InputSchema{
			Type: "object",
			Properties: map[string]mcp.Property{
				"agent_id": {Type: "string", Description: "Agent ID"},
				"keyword":  {Type: "string", Description: "Search annotations by keyword"},
				"limit":    {Type: "integer", Description: "Max annotations to return (default 10)"},
			},
			Required: []string{"agent_id"},
		},
	}

	s.RegisterTool(tool, 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")
		}

		opts := gateway.AnnotationListOpts{}
		if v, ok := args["keyword"].(string); ok {
			opts.Keyword = v
		}
		if d, ok := args["limit"].(float64); ok && d > 0 {
			opts.Limit = int(d)
		}

		return gw.ListAnnotations(ctx, apiKey, agentID, opts)
	})
}

func registerCreateAnnotation(s *mcp.Server, gw *gateway.Client) {
	tool := mcp.Tool{
		Name:        "create_annotation",
		Description: "Create a new FAQ annotation — a predefined Q&A pair that overrides the LLM when the user's question matches. Use this to add guaranteed-correct answers for frequently asked questions or issues found in conversations.",
		InputSchema: mcp.InputSchema{
			Type: "object",
			Properties: map[string]mcp.Property{
				"agent_id":  {Type: "string", Description: "Agent ID"},
				"title":     {Type: "string", Description: "Short title for the annotation"},
				"questions": {Type: "array", Description: "List of question variations that should trigger this answer"},
				"answer":    {Type: "string", Description: "The answer to return when matched"},
			},
			Required: []string{"agent_id", "title", "questions", "answer"},
		},
	}

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

		var questions []string
		if qs, ok := args["questions"].([]interface{}); ok {
			for _, q := range qs {
				if s, ok := q.(string); ok {
					questions = append(questions, s)
				}
			}
		}
		if len(questions) == 0 {
			return nil, fmt.Errorf("at least one question is required")
		}

		return gw.CreateAnnotation(ctx, apiKey, agentID, gateway.AnnotationCreateRequest{
			Title:     title,
			Questions: questions,
			Answer:    answer,
		})
	})
}

func registerGetAnnotation(s *mcp.Server, gw *gateway.Client) {
	tool := mcp.Tool{
		Name:        "get_annotation",
		Description: "Get a single annotation by ID — title, questions, answer, hit count, and indexing status.",
		InputSchema: mcp.InputSchema{
			Type: "object",
			Properties: map[string]mcp.Property{
				"agent_id":      {Type: "string", Description: "Agent ID"},
				"annotation_id": {Type: "string", Description: "Annotation ID"},
			},
			Required: []string{"agent_id", "annotation_id"},
		},
	}

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

		return gw.GetAnnotation(ctx, apiKey, agentID, annotationID)
	})
}

func registerUpdateAnnotation(s *mcp.Server, gw *gateway.Client) {
	tool := mcp.Tool{
		Name:        "update_annotation",
		Description: "Update an existing annotation's title, questions, or answer. All fields are optional — only provided fields are updated.",
		InputSchema: mcp.InputSchema{
			Type: "object",
			Properties: map[string]mcp.Property{
				"agent_id":      {Type: "string", Description: "Agent ID"},
				"annotation_id": {Type: "string", Description: "Annotation ID"},
				"title":         {Type: "string", Description: "Short title for the annotation"},
				"questions":     {Type: "array", Description: "List of question variations that should trigger this answer"},
				"answer":        {Type: "string", Description: "The answer to return when matched"},
			},
			Required: []string{"agent_id", "annotation_id"},
		},
	}

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

		req := gateway.AnnotationUpdateRequest{}
		if v, ok := args["title"].(string); ok {
			req.Title = v
		}
		if v, ok := args["answer"].(string); ok {
			req.Answer = v
		}
		if qs, ok := args["questions"].([]interface{}); ok {
			for _, q := range qs {
				if s, ok := q.(string); ok {
					req.Questions = append(req.Questions, s)
				}
			}
		}

		return gw.UpdateAnnotation(ctx, apiKey, agentID, annotationID, req)
	})
}

func registerDeleteAnnotation(s *mcp.Server, gw *gateway.Client) {
	tool := mcp.Tool{
		Name:        "delete_annotation",
		Description: "Delete an annotation by ID. This permanently removes the FAQ override.",
		InputSchema: mcp.InputSchema{
			Type: "object",
			Properties: map[string]mcp.Property{
				"agent_id":      {Type: "string", Description: "Agent ID"},
				"annotation_id": {Type: "string", Description: "Annotation ID"},
			},
			Required: []string{"agent_id", "annotation_id"},
		},
	}

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

		if err := gw.DeleteAnnotation(ctx, apiKey, agentID, annotationID); err != nil {
			return nil, err
		}
		return map[string]string{"status": "deleted"}, nil
	})
}
