import type { CodeWalkthroughFile, CodeWalkthroughNode } from '@redocly/config';

import { matchCodeWalkthroughConditions } from './match-code-walkthrough-conditions';
import { replaceInputsWithValue } from './replace-inputs-with-value';

export function getCodeWalkthroughFileText(
  file: CodeWalkthroughFile,
  state: Record<string, { value: string | boolean }>,
  inputsState: Record<string, { value: string }>,
) {
  const contentChunks: string[] =
    file?.content.flatMap((node) => getChunkText(node, state, inputsState)) ?? [];

  return contentChunks.join('\n');
}

function getChunkText(
  node: CodeWalkthroughNode,
  state: Record<string, { value: string | boolean }>,
  inputsState: Record<string, { value: string }>,
): string[] {
  if (typeof node === 'string') {
    const replacedNode = replaceInputsWithValue(node, inputsState);

    return [replacedNode];
  } else {
    if (!matchCodeWalkthroughConditions(node.condition || {}, state)) {
      return [];
    }

    return node.children.flatMap((child) => getChunkText(child, state, inputsState));
  }
}
