package system

import (
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/mark3labs/mcp-go/mcp"

	"kra/internal/biz/system"
	"kra/internal/conf"
	mcpClient "kra/pkg/mcp/client"
	"kra/pkg/response"
)

// MCP配置（通过InitMcpConfig初始化）
var (
	mcpConfig  *conf.MCP
	serverConf *conf.Server
)

// InitMcpConfig 初始化MCP配置
func InitMcpConfig(mcp *conf.MCP, server *conf.Server) {
	mcpConfig = mcp
	serverConf = server
}

// MCP 创建MCP工具
// @Tags      MCP
// @Summary   创建MCP工具
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      system.AutoMcpTool  true  "MCP工具信息"
// @Success   200   {object}  response.Response{msg=string}  "创建成功"
// @Router    /autoCode/mcp [post]
func (a *AutoCodeMcpApi) MCP(c *gin.Context) {
	var info system.AutoMcpTool
	err := c.ShouldBindJSON(&info)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	toolFilePath, err := autoCodeMcpUsecase.CreateMcp(c.Request.Context(), info)
	if err != nil {
		response.FailWithMessage("创建失败: "+err.Error(), c)
		return
	}
	response.OkWithMessage("创建成功,MCP Tool路径:"+toolFilePath, c)
}

// MCPList 获取MCP工具列表
// @Tags      MCP
// @Summary   获取MCP工具列表
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Success   200   {object}  response.Response{data=interface{}}  "获取成功"
// @Router    /autoCode/mcpList [get]
func (a *AutoCodeMcpApi) MCPList(c *gin.Context) {
	if mcpConfig == nil || !mcpConfig.Enabled {
		response.OkWithData(gin.H{
			"mcpServerConfig": map[string]interface{}{},
			"list":            []interface{}{},
		}, c)
		return
	}

	// 获取服务器地址
	addr := "8888"
	if serverConf != nil && serverConf.Http != nil {
		addr = serverConf.Http.Addr
	}

	baseUrl := fmt.Sprintf("http://127.0.0.1:%s%s", addr, mcpConfig.SsePath)

	client, err := mcpClient.NewClient(baseUrl, "testClient", "v1.0.0", mcpConfig.Name)
	if err != nil {
		response.FailWithMessage("连接MCP服务失败: "+err.Error(), c)
		return
	}
	defer client.Close()

	toolsRequest := mcp.ListToolsRequest{}
	list, err := client.ListTools(c.Request.Context(), toolsRequest)
	if err != nil {
		response.FailWithMessage("获取工具列表失败: "+err.Error(), c)
		return
	}

	mcpServerConfig := map[string]interface{}{
		"mcpServers": map[string]interface{}{
			mcpConfig.Name: map[string]string{
				"url": baseUrl,
			},
		},
	}
	response.OkWithData(gin.H{
		"mcpServerConfig": mcpServerConfig,
		"list":            list,
	}, c)
}

// MCPTest 测试MCP工具
// @Tags      MCP
// @Summary   测试MCP工具
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      object  true  "MCP工具调用参数"
// @Success   200   {object}  response.Response{data=interface{}}  "测试成功"
// @Router    /autoCode/mcpTest [post]
func (a *AutoCodeMcpApi) MCPTest(c *gin.Context) {
	// 定义接口请求结构
	var testRequest struct {
		Name      string                 `json:"name" binding:"required"`      // 工具名称
		Arguments map[string]interface{} `json:"arguments" binding:"required"` // 工具参数
	}

	// 绑定JSON请求体
	if err := c.ShouldBindJSON(&testRequest); err != nil {
		response.FailWithMessage("参数解析失败: "+err.Error(), c)
		return
	}

	if mcpConfig == nil || !mcpConfig.Enabled {
		response.FailWithMessage("MCP服务未启用", c)
		return
	}

	// 获取服务器地址
	addr := "8888"
	if serverConf != nil && serverConf.Http != nil {
		addr = serverConf.Http.Addr
	}

	// 创建MCP客户端
	baseUrl := fmt.Sprintf("http://127.0.0.1:%s%s", addr, mcpConfig.SsePath)
	client, err := mcpClient.NewClient(baseUrl, "testClient", "v1.0.0", mcpConfig.Name)
	if err != nil {
		response.FailWithMessage("创建MCP客户端失败: "+err.Error(), c)
		return
	}
	defer client.Close()

	ctx := c.Request.Context()

	// 初始化MCP连接
	initRequest := mcp.InitializeRequest{}
	initRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION
	initRequest.Params.ClientInfo = mcp.Implementation{
		Name:    "testClient",
		Version: "v1.0.0",
	}

	_, err = client.Initialize(ctx, initRequest)
	if err != nil {
		response.FailWithMessage("初始化MCP连接失败: "+err.Error(), c)
		return
	}

	// 构建工具调用请求
	request := mcp.CallToolRequest{}
	request.Params.Name = testRequest.Name
	request.Params.Arguments = testRequest.Arguments

	// 调用工具
	result, err := client.CallTool(ctx, request)
	if err != nil {
		response.FailWithMessage("工具调用失败: "+err.Error(), c)
		return
	}

	// 处理响应结果
	if len(result.Content) == 0 {
		response.FailWithMessage("工具未返回任何内容", c)
		return
	}

	// 返回结果
	response.OkWithData(result.Content, c)
}
