// MNote debug /tree shell page-mode runtime helpers.

export async function reducePageActionWithRuntime(runtimeContext, action, item) {
  if (runtimeContext.mode !== "page" || !runtimeContext.runtimeReduceEndpoint) {
    return null;
  }
  const runtimeAction = runtimeContext.buildPageRuntimeAction(action, item);
  if (!runtimeAction) return null;
  const response = await fetch(runtimeContext.runtimeReduceEndpoint, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({
      mode: "page",
      requestId: `page-runtime-${Date.now()}`,
      environment: runtimeContext.buildPageRuntimeEnvironment(),
      state: runtimeContext.readPageRuntimeState(action, item),
      action: runtimeAction,
    }),
  });
  if (!response.ok) {
    throw new Error(await runtimeContext.readErrorMessage(response));
  }
  return response.json();
}

export function reconcilePageRuntimeResult(runtimeContext, runtimeResult, item) {
  const result = runtimeContext.normalizePageRuntimeResult(runtimeResult);
  if (!result) return false;
  const previousExpanded = new Set(runtimeContext.expanded);
  let shouldPatchTree = false;
  if (Array.isArray(result.expandedIds)) {
    shouldPatchTree =
      runtimeContext.commitPageExpandedIds(result.expandedIds) || shouldPatchTree;
  }
  const currentFocusedNodeId = runtimeContext.getFocusedNodeId();
  if (result.focusedId && result.focusedId !== currentFocusedNodeId) {
    runtimeContext.setFocusedNodeId(result.focusedId);
    runtimeContext.postPageFocusChange(result.focusedId);
    shouldPatchTree = true;
  }
  const itemNodeId = runtimeContext.normalizeText(item?.nodeId);
  if (
    itemNodeId &&
    previousExpanded.has(itemNodeId) !== runtimeContext.expanded.has(itemNodeId)
  ) {
    runtimeContext.postPageExpandChange(itemNodeId, runtimeContext.expanded.has(itemNodeId));
  }
  if (shouldPatchTree) {
    runtimeContext.patchPageTreeAfterRuntimeState(
      Array.isArray(result.expandedIds) ? [itemNodeId, ...result.expandedIds] : [itemNodeId],
      result.focusedId || runtimeContext.getFocusedNodeId(),
    );
  }
  return shouldPatchTree;
}
