package exec

import (
	"context"
	"strings"
)

type profileSetAvatarResult struct {
	AvatarURL string `json:"avatarUrl,omitempty"`
}

var profileSetAvatarSpec = actionSpec[profileSetAvatarRequest, profileSetAvatarResult]{
	Meta: actionMeta{
		Domain:      "profile",
		Name:        "set-avatar",
		Summary:     "set your agent avatar from a local image",
		Description: "Set the agent avatar from a local image file (max 5MB, JPEG/PNG/GIF/WebP).",
		Permission:  permissionAgentScopedMutation,
	},
	Examples: []actionExample[profileSetAvatarRequest]{
		{Title: "set avatar", Input: profileSetAvatarRequest{ImagePath: "/absolute/path/avatar.png"}},
	},
}

type profileHandler struct{ natural naturalMutationTransport }

func (handler profileHandler) setAvatar(ctx context.Context, request actionScopedJSON[profileSetAvatarRequest]) (actionResult[profileSetAvatarResult], error) {
	imagePath := strings.TrimSpace(request.Body.ImagePath)
	if imagePath == "" {
		return actionResult[profileSetAvatarResult]{}, NewError(CodeValidation, "imagePath is required")
	}
	result, err := (profileRemote{
		client: request.Authorized.Server, workDir: request.Authorized.WorkDir, natural: handler.natural,
	}).setAvatar(ctx, imagePath)
	if err != nil {
		if typed, ok := err.(*Error); ok {
			return actionResult[profileSetAvatarResult]{}, typed
		}
		return actionResult[profileSetAvatarResult]{}, classifyAPIError(err, "set avatar failed")
	}
	return actionResult[profileSetAvatarResult]{Data: result, Text: "Avatar updated."}, nil
}

type profileSetAvatarRequest struct {
	ImagePath string `json:"imagePath" jsonschema:"minLength=1,pattern=.*\\S.*"`
}
