import { prisma } from "@/lib/__mocks__/database";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { cpuMsSince } from "../core/__fixtures__/cpu-time";
import { SurveyImportInputError } from "../core/errors";
import { checkImportDraft } from "../core/final-gate";
import { measureDraftBytes } from "../core/fit-draft";
import { SURVEY_IMPORT_MAX_DRAFT_BYTES, SURVEY_IMPORT_MAX_TEXT_CHARS } from "../limits";
import { loadQsfFixture } from "./__fixtures__/load-fixture";
import {
  PAGE_BREAK,
  blocksElement,
  flowBlock,
  flowElement,
  flowEnd,
  optionsElement,
  question,
  resetFlowIds,
  survey as surveyExport,
} from "./__fixtures__/qsf-builders";
import { loadRecordedPlan, recordedGenerate, refsInPrompt } from "./__fixtures__/recorded-plans";
import type { TQsfPlanGenerate } from "./ai-plan";
import { fitQsfSurveyToCreateLimit } from "./fit-draft";
import { normalizeQualtricsLanguageCode } from "./language-codes";
import { QSF_RECALL_FALLBACK } from "./piped-text";
import { runQsfImport } from "./pipeline";
import { prepareQsfImport } from "./prepare";
import type { TQsfSurvey } from "./qsf-model";

/**
 * What the stages are handed, recorded by pass-through spies. The wall-clock bounds below are coarse
 * sanity checks — another process on the machine stretches every one of them — so each test's real
 * guard is structural: what work reached a stage, or how often the import gave the event loop back.
 */
const seen = vi.hoisted(() => ({
  yields: 0,
  /** This process's CPU time at the last yield, and the most it spent between two yields. */
  cpuAtLastYield: 0,
  longestStretchMs: 0,
  /** Every raw code handed to the language-code normalizer. */
  languageCodeInputs: [] as string[],
  longestPipedScan: 0,
  /** The last sanitized texts, which the plan and the assembly copy from. */
  texts: null as Parameters<typeof import("./fit-draft").fitQsfSurveyToCreateLimit>[1] | null,
  /** For each `planQsfImport` and `assembleQsfDraft` call: whether its survey already fit the body. */
  stages: [] as { stage: "plan" | "assemble"; fits: boolean }[],
}));

vi.mock("server-only", () => ({}));
// The draft's name is looked up in the workspace and suffixed in the user's language (English here).
vi.mock("@/lib/user/locale", () => ({ getUserLocaleOrDefault: vi.fn(async () => "en-US") }));
vi.mock("@/lingodotdev/server", () => import("../core/__fixtures__/lingodotdev-server-en-us"));
vi.mock("@/modules/survey/lib/permission", () => ({ getExternalUrlsPermission: vi.fn(async () => true) }));
vi.mock("node:timers/promises", async (importOriginal) => {
  const original = await importOriginal<typeof import("node:timers/promises")>();
  return {
    ...original,
    setImmediate: (...args: Parameters<typeof original.setImmediate>) => {
      seen.yields += 1;
      const { user, system } = process.cpuUsage();
      seen.longestStretchMs = Math.max(seen.longestStretchMs, (user + system - seen.cpuAtLastYield) / 1000);
      seen.cpuAtLastYield = user + system;
      return original.setImmediate(...args);
    },
  };
});
vi.mock("./language-codes", async (importOriginal) => {
  const original = await importOriginal<typeof import("./language-codes")>();
  return {
    ...original,
    normalizeQualtricsLanguageCode: (raw: string) => {
      seen.languageCodeInputs.push(raw);
      return original.normalizeQualtricsLanguageCode(raw);
    },
  };
});
vi.mock("./piped-text", async (importOriginal) => {
  const original = await importOriginal<typeof import("./piped-text")>();
  return {
    ...original,
    collectEmbeddedDataReferences: (text: string) => {
      seen.longestPipedScan = Math.max(seen.longestPipedScan, text.length);
      return original.collectEmbeddedDataReferences(text);
    },
  };
});

/** Whether a survey, as a stage gets it, already fits the create's body on the fit's own bound. */
const fitsTheBody = (survey: TQsfSurvey, texts: Parameters<typeof fitQsfSurveyToCreateLimit>[1]): boolean =>
  fitQsfSurveyToCreateLimit(structuredClone(survey), texts).issues.length === 0;

vi.mock("./sanitize-text", async (importOriginal) => {
  const original = await importOriginal<typeof import("./sanitize-text")>();
  return {
    ...original,
    sanitizeQsfTexts: async (...args: Parameters<typeof original.sanitizeQsfTexts>) => {
      const texts = await original.sanitizeQsfTexts(...args);
      seen.texts = texts;
      return texts;
    },
  };
});
vi.mock("./ai-plan", async (importOriginal) => {
  const original = await importOriginal<typeof import("./ai-plan")>();
  return {
    ...original,
    planQsfImport: (params: Parameters<typeof original.planQsfImport>[0]) => {
      seen.stages.push({
        stage: "plan",
        fits: seen.texts !== null && fitsTheBody(params.survey, seen.texts),
      });
      return original.planQsfImport(params);
    },
  };
});
vi.mock("./assemble", async (importOriginal) => {
  const original = await importOriginal<typeof import("./assemble")>();
  return {
    ...original,
    assembleQsfDraft: (params: Parameters<typeof original.assembleQsfDraft>[0]) => {
      seen.stages.push({ stage: "assemble", fits: fitsTheBody(params.survey, params.texts) });
      return original.assembleQsfDraft(params);
    },
  };
});

beforeEach(() => {
  vi.mocked(prisma.survey.findMany).mockResolvedValue([]);
  seen.yields = 0;
  seen.languageCodeInputs = [];
  seen.longestPipedScan = 0;
  seen.texts = null;
  seen.stages = [];
});

/**
 * What a synchronous call costs the thread that runs it, in milliseconds: the smaller of the process's
 * CPU time and the wall time. Each alone is stretched by something the call did not do. `process.cpuUsage`
 * sums every thread, so V8's parallel GC helpers, woken by a large allocation, add their time on top of
 * the call's own (a 390,000-key file read 370-390 ms of CPU in 125-180 ms of wall on main); wall time is
 * stretched by whatever else runs on a loaded machine. The thread's own time is at most each of them, so
 * the smaller is the tighter upper bound, and a real regression (seconds) raises both.
 */
const cpuMs = (work: () => unknown): number => {
  const startedAt = performance.now();
  const start = process.cpuUsage();
  work();
  return Math.min(cpuMsSince(start), performance.now() - startedAt);
};

/**
 * The most CPU time the import spends without giving the event loop back: the longest synchronous
 * stretch, which on the server stalls every other request on the pod for as long. Measured in this
 * process's CPU time between two yields rather than in wall time, so a loaded machine — whose other
 * processes stretch every wall-clock reading — does not move it.
 */
const longestStretchMs = async (work: () => Promise<unknown>): Promise<number> => {
  const start = process.cpuUsage();
  seen.cpuAtLastYield = start.user + start.system;
  seen.longestStretchMs = 0;
  await work();
  const end = process.cpuUsage();
  return Math.max(seen.longestStretchMs, (end.user + end.system - seen.cpuAtLastYield) / 1000);
};

const runLarge = (prepared: ReturnType<typeof prepareQsfImport>) =>
  runQsfImport({
    prepared,
    workspaceId: "clxx1234567890123456789012",
    organizationId: "org_1",
    userId: null,
    signal: new AbortController().signal,
    deadlineMs: 120_000,
    onProgress: () => undefined,
    generate: recordedGenerate(loadRecordedPlan("large-150.qsf")),
  });

/**
 * A hostile file: one question with 200 choices and 200 answers, and `variants` `Language` keys that
 * all spell German — `de`, `DE`, ` de`, `\tDe`, … — each with an empty translation of both lists. Case
 * and whitespace variants normalize to one language, so the language cap never fired on them, and
 * every key used to be checked against every choice and answer: ~9 s at 390,000 keys.
 *
 * The `Language` object comes back behind a Proxy that counts how the reader reaches it: `ownKeys`, one
 * listing of its keys, and `get`, one read of a key's value. It has no `getOwnPropertyDescriptor`
 * trap, so the enumerability check `Object.keys` makes on each key, and `Object.hasOwn`, are not
 * counted: those are V8 listing the keys, not the reader reading them.
 */
function buildLanguageVariantsQsf(variants: number) {
  const options = Object.fromEntries(
    Array.from({ length: 200 }, (_, i) => [String(i + 1), { Display: `Option ${i + 1}` }])
  );
  const language: Record<string, unknown> = {};
  const spellings = ["de", "dE", "De", "DE"];
  const space = [" ", "\t", "\n", "\r"];
  for (let index = 0; index * spellings.length < variants; index++) {
    // `index` in base 4, written in whitespace, before each spelling: every key distinct.
    let prefix = "";
    for (let rest = index; rest > 0; rest = Math.floor(rest / 4)) prefix += space[rest % 4];
    for (const spelling of spellings) language[`${prefix}${spelling}`] = { Choices: {}, Answers: {} };
  }
  const reads = { ownKeys: 0, get: 0 };
  const countedLanguage = new Proxy(language, {
    ownKeys: (target) => {
      reads.ownKeys += 1;
      return Reflect.ownKeys(target);
    },
    get: (target, key, receiver) => {
      reads.get += 1;
      return Reflect.get(target, key, receiver);
    },
  });
  const qsf = {
    SurveyEntry: { SurveyName: "Variants", SurveyLanguage: "EN" },
    SurveyElements: [
      {
        Element: "SQ",
        PrimaryAttribute: "QID1",
        Payload: {
          QuestionText: "Rate each",
          QuestionType: "Matrix",
          Selector: "Likert",
          Choices: options,
          Answers: options,
          Language: countedLanguage,
        },
      },
      { Element: "BL", Payload: [{ ID: "BL_1", BlockElements: [{ Type: "Question", QuestionID: "QID1" }] }] },
      { Element: "FL", Payload: { Flow: [{ Type: "Block", ID: "BL_1" }] } },
    ],
  };
  return { qsf, reads, countedLanguage, firstKey: spellings[0] };
}

describe("event loop", () => {
  test("prepareQsfImport never scans a 15 MB text for piped text", async () => {
    // One question text of `${e://` repeated, no closing brace: every match attempt used to scan up to
    // 200 characters on, about 1.7 s for the whole text.
    const qsf = {
      SurveyEntry: { SurveyName: "Long text", SurveyLanguage: "EN" },
      SurveyElements: [
        {
          Element: "SQ",
          PrimaryAttribute: "QID1",
          Payload: { QuestionText: "${e://".repeat(2_500_000), QuestionType: "TE", Selector: "SL" },
        },
        {
          Element: "BL",
          Payload: [{ ID: "BL_1", BlockElements: [{ Type: "Question", QuestionID: "QID1" }] }],
        },
        { Element: "FL", Payload: { Flow: [{ Type: "Block", ID: "BL_1" }] } },
      ],
    };

    // Structural: no text past the sanitizer's length is ever scanned for piped text.
    expect(cpuMs(() => prepareQsfImport(qsf, "long-text.qsf"))).toBeLessThanOrEqual(50);
    expect(seen.longestPipedScan).toBeLessThanOrEqual(SURVEY_IMPORT_MAX_TEXT_CHARS);
  });

  test("prepareQsfImport scans piped text in time linear in the file, its noise spread over many texts", async () => {
    // 302 texts of `${e://` repeated up to the sanitizer's length, no closing brace, in two questions'
    // texts and choices: about 15 MB. Each text is within the cap, so each is scanned; a pipe body that
    // ran up to 200 characters on from every `${` cost about 0.8 s over the file.
    const noise = "${e://".repeat(Math.floor(SURVEY_IMPORT_MAX_TEXT_CHARS / "${e://".length));
    const questions = ["QID1", "QID2"].map((qid) => ({
      Element: "SQ",
      PrimaryAttribute: qid,
      Payload: {
        QuestionText: noise,
        QuestionType: "MC",
        Selector: "SAVR",
        Choices: Object.fromEntries(
          Array.from({ length: 150 }, (_, i) => [String(i + 1), { Display: noise }])
        ),
      },
    }));
    const qsf = {
      SurveyEntry: { SurveyName: "Spread noise", SurveyLanguage: "EN" },
      SurveyElements: [
        ...questions,
        {
          Element: "BL",
          Payload: [
            {
              ID: "BL_1",
              BlockElements: ["QID1", "QID2"].map((qid) => ({ Type: "Question", QuestionID: qid })),
            },
          ],
        },
        { Element: "FL", Payload: { Flow: [{ Type: "Block", ID: "BL_1" }] } },
      ],
    };

    const used = cpuMs(() => prepareQsfImport(qsf, "spread-noise.qsf"));

    // Structural: every text is scanned, none past the cap; the bound is on each scan's cost.
    expect(seen.longestPipedScan).toBe(noise.length);
    // Coarse: ~15 ms of scanning, where a body that ran on to 200 characters took about 800.
    expect(used).toBeLessThanOrEqual(200);
  });

  test("prepareQsfImport cuts every other long string from the file before it trims or matches it", async () => {
    // Names cut before they are trimmed; codes, numbers, a message reference and a URL refused by
    // their length first.
    const pad = " ".repeat(3_000_000);
    const qsf = {
      SurveyEntry: { SurveyName: `Name${pad}`, SurveyLanguage: `${pad}EN` },
      SurveyElements: [
        {
          Element: "SQ",
          PrimaryAttribute: "QID1",
          Payload: {
            QuestionText: "Q",
            DataExportTag: `Q1${pad}`,
            QuestionType: "TE",
            Selector: "SL",
            Language: { [`${pad}DE`]: { QuestionText: "F" } },
          },
        },
        {
          Element: "BL",
          Payload: [{ ID: "BL_1", BlockElements: [{ Type: "Question", QuestionID: "QID1" }] }],
        },
        {
          Element: "FL",
          Payload: {
            Flow: [
              { Type: "EmbeddedData", EmbeddedData: [{ Field: `f${pad}` }] },
              { Type: "Block", ID: "BL_1" },
            ],
          },
        },
        { Element: "SO", Payload: { EOSMessage: `MS_${"a".repeat(3_000_000)}`, EOSRedirectURL: `${pad}x` } },
      ],
    };

    expect(cpuMs(() => prepareQsfImport(qsf, "long-strings.qsf"))).toBeLessThanOrEqual(50);
  });

  // Normalizing every key against 400 options took about half a second at 20,000 variants and about 9 s at
  // 390,000. The work is counted rather than timed: the reader lists the keys once (V8's enumeration still
  // grows with their number) and refuses the map on that count before reading any value, with the same
  // counts at both sizes.
  test.each([20_000, 390_000])(
    "prepareQsfImport refuses %i Language key variants on their count, before reading any key",
    async (variants) => {
      const { qsf, reads, countedLanguage, firstKey } = buildLanguageVariantsQsf(variants);
      let refused: unknown;

      try {
        prepareQsfImport(qsf, "variants.qsf");
      } catch (error) {
        refused = error;
      }

      expect(refused).toBeInstanceOf(SurveyImportInputError);
      expect((refused as SurveyImportInputError).invalidParams[0].name).toBe(
        "file.SurveyElements.0.Payload.Language"
      );
      // No `Language` key reaches the normalizer (every variant is whitespace then some casing of "de").
      // The keys are listed once and no value is read.
      expect(seen.languageCodeInputs.filter((raw) => /^\s*de$/i.test(raw))).toEqual([]);
      expect(reads).toEqual({ ownKeys: 1, get: 0 });
      // The `get` count can move: a read through the same Proxy is counted, so the 0 above is the reader's.
      expect(countedLanguage[firstKey]).toBeDefined();
      expect(reads.get).toBe(1);
    }
  );

  test("prepareQsfImport holds it for at most ~50 ms on the largest file", async () => {
    const qsf = loadQsfFixture("large-150.qsf");

    // Coarse, cold: ~7 ms on an idle laptop. Cold, the CPU time also counts the JIT compiling on other
    // threads, which a loaded machine stretches, so the plan's 50 ms budget is held warm, below.
    expect(cpuMs(() => prepareQsfImport(qsf, "large-150.qsf"))).toBeLessThan(1_000);
    // The plan's budget, in CPU time so other processes do not stretch it: ~2 ms warm. The best of five:
    // the process's CPU time also counts its GC and compiler threads, and one of their spikes under a
    // coverage run once measured 123 ms. A real slowdown fails every run.
    const warmRuns = Array.from({ length: 5 }, () => cpuMs(() => prepareQsfImport(qsf, "large-150.qsf")));
    expect(Math.min(...warmRuns)).toBeLessThanOrEqual(50);
  });

  test(
    "runQsfImport never holds it for long, sanitizer included, the AI mocked",
    { timeout: 30_000 },
    async () => {
      // A first run pays for JIT and for compiling the survey schemas, once per process.
      await runLarge(prepareQsfImport(loadQsfFixture("large-150.qsf"), "large-150.qsf"));
      const prepared = prepareQsfImport(loadQsfFixture("large-150.qsf"), "large-150.qsf");
      // Every text with real markup, choices included: over half a second of sanitizing in all, in
      // about 600 small texts. It has to come in slices.
      for (const text of prepared.survey.texts.values()) {
        text.byLanguage.set(prepared.survey.defaultLanguage, "<span>x</span>".repeat(30));
      }

      seen.yields = 0;
      const stretchMs = await longestStretchMs(() => runLarge(prepared));

      // Structural: over half a second of sanitizing comes in ~10 ms slices, so the import gives the
      // event loop back dozens of times; one that stops yielding does so a handful of times.
      expect(seen.yields).toBeGreaterThanOrEqual(20);
      // Coarse: ~20 ms warm, the longest stretch one synchronous check of the draft; unsliced, the
      // sanitizing alone is over half a second.
      expect(stretchMs).toBeLessThan(400);
    }
  );
});

// Here rather than beside the other pipeline tests: these build and assemble multi-megabyte surveys,
// and a file's tests run one after another, so they never load the machine while an event-loop
// measurement above runs.
describe("a draft too large for the create's request body", () => {
  /** 49 Qualtrics codes for distinct survey languages, from what the reader makes of them. */
  const translationCodes = (): string[] => {
    const seen = new Map<string, string>();
    for (const region of ["", "-AT", "-CH", "-BE", "-US", "-GB"]) {
      for (const code of [
        "AR",
        "BG",
        "CS",
        "DA",
        "DE",
        "EL",
        "ES",
        "ET",
        "FI",
        "FR",
        "HE",
        "HI",
        "HR",
        "HU",
      ]) {
        const normalized = normalizeQualtricsLanguageCode(`${code}${region}`);
        if (normalized && normalized !== "en-US" && !seen.has(normalized))
          seen.set(normalized, `${code}${region}`);
      }
    }
    return [...seen.values()].slice(0, 49);
  };

  /** `questions` multiple choice questions of `options` options, on pages of 10, in `languages`. */
  const buildQsf = (shape: {
    questions: number;
    options: number;
    languages: string[];
    textChars: number;
  }) => {
    const pad = "x".repeat(shape.textChars);
    const refs = Array.from({ length: shape.questions }, (_, q) => `QID${q + 1}`);
    const elements = refs.map((ref, q) => {
      const choices = Object.fromEntries(
        Array.from({ length: shape.options }, (_, i) => [
          String(i + 1),
          { Display: `Option ${i + 1} of ${q}` },
        ])
      );
      const language = Object.fromEntries(
        shape.languages.map((code) => [
          code,
          { QuestionText: `${code} question ${q} ${pad}`, Choices: choices },
        ])
      );
      return {
        Element: "SQ",
        PrimaryAttribute: ref,
        Payload: {
          QuestionText: `Question ${q} ${pad}`,
          DataExportTag: `Q${q + 1}`,
          QuestionType: "MC",
          Selector: "SAVR",
          Choices: choices,
          Language: language,
        },
      };
    });
    const blocks = Array.from({ length: Math.ceil(shape.questions / 10) }, (_, b) => ({
      ID: `BL_${b}`,
      Description: `Block ${b}`,
      BlockElements: refs.slice(b * 10, b * 10 + 10).map((ref) => ({ Type: "Question", QuestionID: ref })),
    }));
    return {
      SurveyEntry: { SurveyName: "Large", SurveyLanguage: "EN" },
      SurveyElements: [
        ...elements,
        { Element: "BL", Payload: blocks },
        { Element: "FL", Payload: { Flow: blocks.map((block) => ({ Type: "Block", ID: block.ID })) } },
      ],
    };
  };

  const answerAsMultipleChoice: TQsfPlanGenerate = async (request) => ({
    object: {
      questions: refsInPrompt(request.prompt).map((ref) => ({
        ref,
        type: "multipleChoiceSingle",
        required: false,
        choicesFrom: "choices",
        rowsFrom: null,
        columnsFrom: null,
        otherChoiceKey: null,
        noneChoiceKey: null,
        labelKey: null,
        excludedKeys: [],
        contactFields: [],
        inputType: null,
        scale: null,
        range: null,
        format: null,
        logicNotes: [],
      })),
      skipped: [],
      pages: [],
    },
  });

  /** Run the import, measuring the longest the event loop is held once the stream is open. */
  const runQsf = async (qsf: Record<string, unknown>) => {
    const prepared = prepareQsfImport(qsf, "large.qsf");
    let result: Awaited<ReturnType<typeof runQsfImport>> | undefined;
    const stretchMs = await longestStretchMs(async () => {
      result = await runQsfImport({
        prepared,
        workspaceId: "clxx1234567890123456789012",
        organizationId: "org_1",
        userId: "user_1",
        signal: new AbortController().signal,
        deadlineMs: 120_000,
        onProgress: () => undefined,
        generate: answerAsMultipleChoice,
      });
    });
    if (!result) throw new Error("the import returned nothing");
    return { ...result, stretchMs };
  };

  test(
    "cuts languages, last declared first, from 200 questions of 15 options in 50 languages",
    { timeout: 120_000 },
    async () => {
      const result = await runQsf(
        buildQsf({ questions: 200, options: 15, languages: translationCodes(), textChars: 0 })
      );

      // Structural: the survey was cut to fit before it was planned, so the plan and the assembly only
      // ever saw what fits one create body.
      expect(seen.stages.map((stage) => stage.stage)).toEqual(["plan", "assemble"]);
      expect(seen.stages.every((stage) => stage.fits)).toBe(true);
      // Coarse: the longest stretch left is the create's own request schema on that ~2 MB draft, ~1.3 s;
      // uncut, the 4.3 MB draft's took about 4.5 s.
      expect(result.stretchMs).toBeLessThan(3_000);
      expect(measureDraftBytes(result.payload)).toBeLessThanOrEqual(SURVEY_IMPORT_MAX_DRAFT_BYTES);
      expect(result.report.summary.questions).toBe(200);
      const cut = result.report.issues.filter(
        (issue) => issue.code === "language_skipped" && issue.params?.cause === "draft_too_large"
      );
      expect(cut.length).toBeGreaterThan(0);
      expect(result.report.summary.languages).toHaveLength(50 - cut.length);
      expect(result.report.summary.languages[0]).toBe("en-US");
      expect(cut.map((issue) => issue.params?.code)).not.toContain("en-US");
      expect(checkImportDraft(result.payload)).toEqual([]);
    }
  );

  test(
    "cuts trailing questions from a one-language survey of very long texts",
    { timeout: 60_000 },
    async () => {
      // 200 questions of 20,000-character texts: about 4 MB in one language.
      const result = await runQsf(buildQsf({ questions: 200, options: 2, languages: [], textChars: 20_000 }));

      expect(seen.stages.map((stage) => stage.stage)).toEqual(["plan", "assemble"]);
      expect(seen.stages.every((stage) => stage.fits)).toBe(true);
      // Coarse: few, long texts are cheap to check, and sliced everywhere else. ~60 ms.
      expect(result.stretchMs).toBeLessThan(300);
      expect(measureDraftBytes(result.payload)).toBeLessThanOrEqual(SURVEY_IMPORT_MAX_DRAFT_BYTES);
      const cut = result.report.issues.filter(
        (issue) => issue.code === "question_skipped" && issue.params?.cause === "draft_too_large"
      );
      expect(cut.length).toBeGreaterThan(0);
      expect(result.report.summary.questions).toBe(200 - cut.length);
      // Cut before planning, the trailing run of questions, in flow order.
      expect(cut.map((issue) => issue.questionTag)).toEqual(
        Array.from({ length: cut.length }, (_, index) => `Q${200 - cut.length + index + 1}`)
      );
      expect(result.payload.blocks.flatMap((block) => block.elements).at(-1)?.id).toBe(
        `Q${200 - cut.length}`
      );
      expect(checkImportDraft(result.payload)).toEqual([]);
    }
  );

  test(
    "shows the fallback for a pipe to a question cut to fit, in the ending and in kept questions, and says so",
    { timeout: 60_000 },
    async () => {
      // 120 questions of 20,000-character texts in one language: the trailing ones are cut before
      // planning. The end message recalls two of them and a kept one; Q70 recalls a kept and a cut one.
      const words = (seed: string, length: number) =>
        Array.from({ length: Math.ceil(length / 4) }, (_, i) => `${seed}w${i}`)
          .join(" ")
          .slice(0, length);
      const pipe = (qid: string) => `\${q://${qid}/ChoiceGroup/SelectedChoices}`;
      const extra: Record<number, string> = {
        70: `Recall of kept Q2: [${pipe("QID2")}] and of cut Q118: [${pipe("QID118")}].`,
      };
      resetFlowIds();
      const elements: string[] = [];
      const questions = Array.from({ length: 120 }, (_, index) => {
        const n = index + 1;
        elements.push(`QID${n}`);
        if (n % 5 === 0 && n < 120) elements.push(PAGE_BREAK);
        return question({
          qid: `QID${n}`,
          text: `Question ${n}: ${extra[n] ?? ""} ${words(`q${n}`, 20_000)}`,
          type: "MC",
          selector: "SAVR",
          choices: [1, 2, 3, 4].map((option) => ({ display: `Option ${option} of ${n}` })),
        });
      });
      const endMessage = `Cut Q118 said [${pipe("QID118")}], cut Q120 said [${pipe("QID120")}], kept Q2 said [${pipe("QID2")}].`;
      const qsf = surveyExport(
        "Recall of cut",
        "EN",
        [
          ...questions,
          blocksElement([{ id: "BL_1", description: "All", type: "Default", elements }]),
          flowElement([flowBlock("BL_1"), flowEnd()]),
          optionsElement({ EOSMessage: endMessage }),
        ],
        120
      );

      const result = await runQsf(qsf);

      const cut = result.report.issues
        .filter((issue) => issue.code === "question_skipped" && issue.params?.cause === "draft_too_large")
        .map((issue) => issue.questionTag);
      expect(cut).toEqual(expect.arrayContaining(["Q118", "Q120"]));
      expect(cut).not.toContain("Q70");

      const ending = result.payload.endings[0];
      const endText = ending?.type === "endScreen" ? ending.headline["en-US"] : "";
      expect(endText).toContain(
        `Cut Q118 said [${QSF_RECALL_FALLBACK}], cut Q120 said [${QSF_RECALL_FALLBACK}]`
      );
      expect(endText).toContain("kept Q2 said [#recall:Q2/fallback:...#]");
      const q70 = result.payload.blocks
        .flatMap((block) => block.elements)
        .find((element) => element.id === "Q70");
      expect(q70?.headline["en-US"]).toContain(
        `Recall of kept Q2: [#recall:Q2/fallback:...#] and of cut Q118: [${QSF_RECALL_FALLBACK}].`
      );
      expect(result.report.issues).toEqual(
        expect.arrayContaining([
          { code: "piped_text_removed", severity: "warning", params: { count: 2, subject: "ending" } },
          { code: "piped_text_removed", severity: "warning", questionTag: "Q70", params: { count: 1 } },
        ])
      );
      expect(checkImportDraft(result.payload)).toEqual([]);
    }
  );
});
