package com.easyagents.agent.runtime.tool.operate;

import com.easyagents.agent.runtime.AgentRuntimeException;
import io.agentscope.core.message.ToolResultBlock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 内置工作区工具的稳定错误结果工厂。
 */
final class WorkspaceToolResults {

    private static final Logger logger = LoggerFactory.getLogger(WorkspaceToolResults.class);

    private WorkspaceToolResults() {
    }

    /**
     * 将内部异常转换为不含宿主路径的稳定错误对象。
     *
     * @param error 内部异常
     * @return Tool 错误结果
     */
    static ToolResultBlock error(AgentRuntimeException error) {
        if (error instanceof WorkspaceToolException typed) {
            if (typed.getCause() != null) {
                logger.error("Workspace tool failed with code {}", typed.code(), typed);
            }
            return error(typed.code(), typed.getMessage(), typed.retryable());
        }
        logger.error("Unexpected workspace tool failure", error);
        return error("WORKSPACE_OPERATION_FAILED", "Workspace operation failed.", false);
    }

    /**
     * 创建稳定错误结果。
     *
     * @param code 错误码
     * @param message 安全错误信息
     * @param retryable 是否可重试
     * @return Tool 错误结果
     */
    static ToolResultBlock error(String code, String message, boolean retryable) {
        String json = "{\"code\":\"" + escape(code) + "\",\"message\":\""
                + escape(message) + "\",\"retryable\":" + retryable + "}";
        return ToolResultBlock.error(json);
    }

    private static String escape(String value) {
        if (value == null) {
            return "";
        }
        return value.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "\\r");
    }
}
