package exec

import (
	"errors"
	"strings"

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

// taskChannelTargetInvalidCode is the stable server code (taskboard
// ErrInvalidChannelTarget) signalling a Task board channel reference that is
// not a usable #channel target — a bare name, an unknown identifier, or a DM.
// Duplicated from the agent-runtime contract
// (internal/store/taskboard.InvalidChannelTargetCode); desktop and the agent
// runtime are separate modules.
const taskChannelTargetInvalidCode = "task_channel_target_invalid"

// taskChannelFormatHint is stable, authored guidance returned only for a Task
// channel-target failure — never for task-not-found/status/cursor errors. It is
// not the server's raw message, so it keeps the no-leak invariant that
// classifyAPIError upholds.
const taskChannelFormatHint = "tasks require a #channel target, e.g. #agentteam-in-agentteam (DMs are unsupported)"

func classifyTaskError(err error, problem string) *Error {
	if typed, ok := err.(*Error); ok {
		return typed
	}
	classified := classifyAPIError(err, problem)
	// Attach a channel-format hint only when the server reported the stable
	// invalid-channel-target code, so unrelated validation/not-found errors are
	// not mislabelled as channel problems.
	if classified != nil && strings.TrimSpace(classified.Hint) == "" {
		var apiErr *apiclient.APIError
		if errors.As(err, &apiErr) && apiErr.Code == taskChannelTargetInvalidCode {
			classified.Hint = taskChannelFormatHint
		}
	}
	return classified
}
