import { logger } from "./logger.js";
const DEFAULT_CLAIM_ATTEMPTS = 5;
const DEFAULT_CLAIM_RETRY_DELAY_MS = 200;
const MAX_CLAIM_ATTEMPTS = 10;
const MAX_CLAIM_RETRY_DELAY_MS = 5_000;
function shouldClaimLaunchBinding() {
    return process.env.AWS_MCP_CLAIM_LAUNCH_BINDING !== "false";
}
function normalizeBridgeBaseUrl(serverConfig) {
    return String(serverConfig.runtimeBridgeBaseUrl || "").trim().replace(/\/$/, "");
}
function readBoundedNumberEnv(key, fallback, min, max) {
    const parsed = Number.parseInt(String(process.env[key] || ""), 10);
    if (!Number.isFinite(parsed)) {
        return fallback;
    }
    return Math.min(Math.max(parsed, min), max);
}
function getClaimAttempts() {
    return readBoundedNumberEnv("AWS_MCP_LAUNCH_BINDING_CLAIM_ATTEMPTS", DEFAULT_CLAIM_ATTEMPTS, 1, MAX_CLAIM_ATTEMPTS);
}
function getClaimRetryDelayMs() {
    return readBoundedNumberEnv("AWS_MCP_LAUNCH_BINDING_CLAIM_RETRY_DELAY_MS", DEFAULT_CLAIM_RETRY_DELAY_MS, 0, MAX_CLAIM_RETRY_DELAY_MS);
}
function delay(ms) {
    if (ms <= 0) {
        return Promise.resolve();
    }
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}
function buildClaimRequestBody(agentConfig, serverConfig) {
    const body = {
        workspacePath: String(agentConfig.workspacePath || "").trim(),
        serverUrl: serverConfig.serverUrl,
    };
    const agentId = String(agentConfig.agentId || "").trim();
    if (agentId) {
        body.agentId = agentId;
    }
    return body;
}
function shouldRetryClaimResponse(response) {
    return response.status === 404 || response.status >= 500;
}
export async function claimRuntimeLaunchBinding(agentConfig, serverConfig) {
    if (!shouldClaimLaunchBinding()) {
        return null;
    }
    const bridgeBaseUrl = normalizeBridgeBaseUrl(serverConfig);
    if (!bridgeBaseUrl) {
        logger.warn("[RuntimeLaunchBinding] 已请求认领启动绑定，但未配置 AWS_RUNTIME_BRIDGE_BASE_URL");
        return null;
    }
    const workspacePath = String(agentConfig.workspacePath || "").trim();
    if (!workspacePath) {
        logger.warn("[RuntimeLaunchBinding] workspacePath 为空，无法认领启动绑定");
        return null;
    }
    const body = buildClaimRequestBody(agentConfig, serverConfig);
    const attempts = getClaimAttempts();
    const retryDelayMs = getClaimRetryDelayMs();
    for (let attempt = 1; attempt <= attempts; attempt += 1) {
        let response;
        try {
            response = await fetch(`${bridgeBaseUrl}/runtime/binding/claim-agent`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(body),
            });
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            if (attempt < attempts) {
                logger.warn(`[RuntimeLaunchBinding] 无法连接 runtime-bridge 认领启动绑定，准备重试 ${attempt}/${attempts}: ${errorMessage}`);
                await delay(retryDelayMs);
                continue;
            }
            logger.warn(`[RuntimeLaunchBinding] 无法连接 runtime-bridge 认领启动绑定: ${errorMessage}`);
            return null;
        }
        if (!response.ok) {
            if (shouldRetryClaimResponse(response) && attempt < attempts) {
                logger.warn(`[RuntimeLaunchBinding] 启动绑定暂不可用，准备重试 ${attempt}/${attempts}: ${response.status} ${response.statusText}`);
                await delay(retryDelayMs);
                continue;
            }
            if (response.status === 404) {
                logger.warn(`[RuntimeLaunchBinding] 未找到待认领启动绑定: ${workspacePath}`);
                return null;
            }
            throw new Error(`Failed to claim runtime launch binding: ${response.status} ${response.statusText}`);
        }
        const payload = (await response.json());
        if (!payload.agentId) {
            throw new Error(payload.error || "runtime-bridge did not return agentId");
        }
        return payload;
    }
    return null;
}
//# sourceMappingURL=runtime-launch-binding.js.map