package invocation

import (
	"github.com/tidbcloud/AgentTeam/internal/api"
	"github.com/tidbcloud/AgentTeam/internal/store/storeerr"
	"github.com/tidbcloud/AgentTeam/internal/workflow/invocationmanage"
	"github.com/tidbcloud/AgentTeam/internal/workflow/publicerr"
)

// publicError constructs a canonical API-layer domain error that the shared
// classifier projects into the canonical public Workflow error contract.
func publicError(status int, code string, problem string) error {
	return publicerr.WorkflowError{
		Kind: storeerr.ErrBadRequest, Status: status, Code: code, Problem: problem,
	}
}

func classifyError(err error) (api.ErrorResponse, bool) {
	classified, ok := publicerr.Classify(err, publicerr.Options{
		Stage:       publicerr.StageInvocation,
		DefaultCode: "invocation_request_failed",
		ProtectedSelectors: map[string]string{
			string(invocationmanage.ErrorCodeNotFound):  string(invocationmanage.ErrorCodeNotFound),
			string(invocationmanage.ErrorCodeForbidden): string(invocationmanage.ErrorCodeNotFound),
		},
		ProtectedNotFoundCode: string(invocationmanage.ErrorCodeNotFound),
	})
	if !ok {
		return api.ErrorResponse{}, false
	}
	return workflowErrorResponse(classified), true
}

// workflowErrorResponse maps a canonical public Workflow classification into the
// shared API error envelope, carrying every canonical contract field.
func workflowErrorResponse(classified publicerr.Classified) api.ErrorResponse {
	response := api.ErrorResponse{
		Status: classified.Status, Message: classified.Error.Problem,
		Code: classified.Error.Code, Details: classified.Details,
		Stage: string(classified.Error.Stage), Path: classified.Error.Path,
		Hint: classified.Error.Hint, Retryable: classified.Error.Retryable,
		Diagnostics: classified.Error.Diagnostics,
	}
	if classified.Error.Truncation != nil {
		response.Truncation = classified.Error.Truncation
	}
	return response
}
