package mcp

import (
	"errors"
	"net/http"
	"strings"

	"github.com/tidbcloud/AgentTeam/desktop/internal/types"
	"github.com/tidbcloud/AgentTeam/desktop/internal/wire/apiclient"
)

func knowledgeMCPToolError(err error) *types.MCPToolResult {
	var apiErr *apiclient.APIError
	if !errors.As(err, &apiErr) {
		return toolError(err.Error())
	}
	code := strings.TrimSpace(apiErr.Code)
	details := apiErr.Details
	if code == "" && apiErr.Stage() == "" && apiErr.StatusCode == http.StatusNotFound && strings.HasSuffix(apiErr.Path, "/agent-thread/upstream") {
		code = "route_missing"
		details = map[string]any{"stage": "agentteam_route_resolution"}
	}
	if code == "" && apiErr.Stage() == "" {
		return toolError(err.Error())
	}
	displayErr := *apiErr
	displayErr.Code = code
	displayErr.Details = details
	result := types.NewToolError(displayErr.Error())
	result.StructuredContent = map[string]any{
		"error": strings.TrimSpace(apiErr.Message), "code": code,
		"details": details, "http_status": apiErr.StatusCode,
	}
	return result
}
