All files / player-browser/src/collection course-maker.ts

94.33% Statements 150/159
83.63% Branches 92/110
98.03% Functions 50/51
100% Lines 132/132

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557                                                                                      50x     50x             50x             50x           50x     50x                                                                                     18x         18x 18x 18x 18x 18x         27x         32x       3x       7x         6x         1x 1x         11x                           3x 3x 3x 1x 3x 1x 3x         12x 12x         21x 20x   20x 20x 20x             21x 19x 19x 19x         1x 1x 1x         1x 1x 1x         1x 1x 1x               9x 9x   9x 9x       9x 8x 8x 8x 8x 8x         2x 2x 2x         1x 1x         1x 1x         1x 1x         3x 3x                                 10x 65x 1x 1x   10x 10x 8x 8x                 10x 9x 10x 9x 9x         22x                 3x                   5x 2x 2x 2x               3x 2x 1x 3x 3x                 3x 3x 3x 3x 3x                 3x 3x 2x 2x 2x   1x 1x 1x               2x 1x         2x 2x 2x 2x       14x 9x 9x 9x       81x           117x                                     80x                                                   117x         6x 1x                                       6x     6x 6x 6x                                                 28x     28x 28x 28x                             2x                       13x     20x          
import {
  appendCourseDraftStage,
  createCourseDraft,
  DEFAULT_LR2_RANDOM_MIX_SETTINGS,
  DEFAULT_RANDOM_MIX_CONDITIONS,
  defaultCourseMakerConstraints,
  normalizeRandomMixConditions,
  drawLR2RandomMix,
  LR2_RANDOM_MIX_NAME,
  normalizeLR2RandomMixSettings,
  resolveLR2RandomMixSettings,
  stepLR2RandomMixSetting,
  finishCourseDraft,
  parseLR2NonstopConnections,
  removeLastCourseDraftStage,
  stepLR2NonstopConnection,
  withCourseConstraints,
  withNonstopConnection,
  type CourseChartLookup,
  type CourseConstraint,
  type CourseDefinition,
  type CourseDraft,
  type CourseDraftAppendFailure,
  type CourseKind,
  type LR2RandomMixChart,
  type LR2RandomMixDrawResult,
  type LR2RandomMixSetting,
  type LR2RandomMixSettings,
  type NonstopConnection,
  type RandomMixCandidate,
  type RandomMixConditions,
} from '@be-music/player-engine/course';
import {
  resolveLibraryChartDifficulty,
  resolveLibraryChartPlayVariant,
  type LibraryChart,
  type LibraryCourse,
  type LibraryFolder,
} from '@be-music/player-scene-model';
import { resolveChartBPMRange } from '../chart/bpm-range.ts';
import { resolveCourseEntry } from './course.ts';
 
/** The course folders the player's own courses are listed in, in LR2's order (its `course1-3.lr2folder`). */
export const COURSE_MAKER_KINDS: readonly CourseKind[] = ['expert', 'nonstop', 'grade'];
 
/** The label of each course folder, as its folder bar shows it. */
export const COURSE_MAKER_FOLDER_LABELS: Readonly<Record<CourseKind, string>> = {
  expert: 'MY COURSES',
  nonstop: 'MY NONSTOP',
  grade: 'MY DAN',
};
 
/** What a course saved without a name is called, before its number in its folder. */
const UNNAMED_COURSE_LABELS: Readonly<Record<CourseKind, string>> = {
  expert: 'COURSE',
  nonstop: 'NONSTOP',
  grade: 'DAN',
};
 
/** The title of a course folder's NEW COURSE bar. */
export const NEW_COURSE_NAME = 'NEW COURSE';
 
/**
 * What the course name reads while it is empty: LR2 starts a course with a prompt to type its title (OpenLR2
 * L12148-L12177).
 */
export const COURSE_NAME_PROMPT = 'Type the course title';
 
/** The course folders LR2 lists a RANDOM MIX bar in (OpenLR2 L18168-L18191: not GRADE). */
export const RANDOM_MIX_KINDS: readonly ('expert' | 'nonstop')[] = ['expert', 'nonstop'];
 
/**
 * What changed in a {@link CourseMaker}: the course being made, the saved courses, or the settings (the default
 * connection, the RANDOM MIX settings).
 */
export type CourseMakerChange = 'draft' | 'courses' | 'settings';
 
/** Why a song cannot join a course being made: `not-making` when no course is being made. */
export type CourseMakerAppendFailure = CourseDraftAppendFailure | 'not-making';
 
export interface CourseMakerOptions {
  /** The player's saved courses, newest first. */
  courses?: readonly CourseDefinition[];
  /** The connection a new NONSTOP course gets after each stage (LR2's button 268). Default `fade`. */
  defaultConnection?: NonstopConnection;
  /** The RANDOM MIX settings (LR2's buttons 260-266). Default LR2's. */
  randomMixSettings?: LR2RandomMixSettings;
  /** The conditions the RANDOM MIX dialog last confirmed. Default `DEFAULT_RANDOM_MIX_CONDITIONS`. */
  randomMixConditions?: RandomMixConditions;
  /** A song's chart MD5, which a course keys its stages by; `undefined` when it cannot be hashed. */
  md5Of: (chartEntry: LibraryChart) => Promise<string | undefined>;
  /** Called after every change, so a host can save the courses and redraw. */
  onChange?: (change: CourseMakerChange) => void;
}
 
/**
 * The player's own courses and the course being made, as LR2's select screen keeps them (`isMakingCourse`, its
 * `expert` / `nonstop` / `grade` tables). Making a course: {@link start} it from a NEW COURSE bar, {@link append}
 * songs (decide on a song bar), {@link removeLast} (LR2's right click), then {@link finish} (button 230) or
 * {@link cancel} (231). A saved course can be renamed (text 170), deleted (button 233) and, when NONSTOP, have each
 * connection stepped (buttons 240-248). {@link releaseCourse} flags a saved course for IR (button 253, its `release`),
 * once and for good, and the flagged course is then read-only: its connections and constraints, which key its ranking,
 * no longer change, though it can still be renamed and deleted, as in LR2. A RANDOM MIX bar {@link drawRandomMix draws} a course by the
 * {@link randomMixSettings} and keeps it as the newest course of its kind, in place of the previous draw.
 */
export class CourseMaker {
  private savedCourses: CourseDefinition[];
  private current: CourseDraft | undefined;
  private connection: NonstopConnection;
  private mixSettings: LR2RandomMixSettings;
  private mixConditions: RandomMixConditions;
  /** The last RANDOM MIX drawn in each folder, among {@link savedCourses}: the next draw there replaces it. */
  private lastRandomMixes = new Set<CourseDefinition>();
 
  private readonly options: CourseMakerOptions;
 
  constructor(options: CourseMakerOptions) {
    this.options = options;
    this.savedCourses = [...(options.courses ?? [])];
    this.connection = options.defaultConnection ?? 'fade';
    this.mixSettings = { ...(options.randomMixSettings ?? DEFAULT_LR2_RANDOM_MIX_SETTINGS) };
    this.mixConditions = normalizeRandomMixConditions(options.randomMixConditions ?? DEFAULT_RANDOM_MIX_CONDITIONS);
  }
 
  /** The saved courses, newest first. */
  get courses(): readonly CourseDefinition[] {
    return this.savedCourses;
  }
 
  /** The course being made, or `undefined` when none is. */
  get draft(): CourseDraft | undefined {
    return this.current;
  }
 
  get defaultConnection(): NonstopConnection {
    return this.connection;
  }
 
  get randomMixSettings(): LR2RandomMixSettings {
    return this.mixSettings;
  }
 
  /** The conditions the RANDOM MIX dialog last confirmed: the dialog opens on them. */
  get randomMixConditions(): RandomMixConditions {
    return this.mixConditions;
  }
 
  /** Keeps the conditions the RANDOM MIX dialog was confirmed with. */
  setRandomMixConditions(conditions: RandomMixConditions): void {
    this.mixConditions = normalizeRandomMixConditions(conditions);
    this.emit('settings');
  }
 
  /** The saved courses that are the last RANDOM MIX drawn in their folder (the next draw there replaces them). */
  get randomMixes(): readonly CourseDefinition[] {
    return this.savedCourses.filter((course) => this.lastRandomMixes.has(course));
  }
 
  /**
   * Replaces the saved courses, the default connection and the RANDOM MIX settings with ones read back from storage (no
   * change is emitted). `randomMixes` are those of `courses` that are a folder's last RANDOM MIX.
   */
  restore(saved: {
    courses: readonly CourseDefinition[];
    defaultConnection?: NonstopConnection;
    randomMixSettings?: LR2RandomMixSettings;
    randomMixConditions?: RandomMixConditions;
    randomMixes?: readonly CourseDefinition[];
  }): void {
    this.savedCourses = [...saved.courses];
    if (saved.defaultConnection !== undefined) this.connection = saved.defaultConnection;
    if (saved.randomMixSettings !== undefined)
      this.mixSettings = normalizeLR2RandomMixSettings(saved.randomMixSettings);
    if (saved.randomMixConditions !== undefined)
      this.mixConditions = normalizeRandomMixConditions(saved.randomMixConditions);
    this.lastRandomMixes = new Set((saved.randomMixes ?? []).filter((course) => this.savedCourses.includes(course)));
  }
 
  /** Starts making a course of `kind`, dropping any course being made. */
  start(kind: CourseKind): void {
    this.current = { ...createCourseDraft(kind), constraints: defaultCourseMakerConstraints(kind) };
    this.emit('draft');
  }
 
  /** Adds a song to the course being made (see `appendCourseDraftStage` for the limits). */
  async append(chartEntry: LibraryChart): Promise<{ ok: true } | { ok: false; reason: CourseMakerAppendFailure }> {
    if (this.current === undefined) return { ok: false, reason: 'not-making' };
    const md5 = await this.options.md5Of(chartEntry);
    // The course may have been finished or cancelled while the chart was hashed.
    const draft = this.current;
    Iif (draft === undefined) return { ok: false, reason: 'not-making' };
    const result = appendCourseDraftStage(draft, {
      md5: md5 ?? '',
      keyMode: Number(resolveLibraryChartPlayVariant(chartEntry)),
      title: chartEntry.title,
      ...(chartEntry.subtitle !== undefined ? { subtitle: chartEntry.subtitle } : {}),
      ...(chartEntry.artist !== undefined ? { artist: chartEntry.artist } : {}),
    });
    if (!result.ok) return result;
    this.current = result.draft;
    this.emit('draft');
    return { ok: true };
  }
 
  /** Drops the last song of the course being made. */
  removeLast(): void {
    Iif (this.current === undefined || this.current.stages.length === 0) return;
    this.current = removeLastCourseDraftStage(this.current);
    this.emit('draft');
  }
 
  /** Sets the constraints of the course being made (beatoraja's course constraints, one per group). */
  setConstraints(constraints: readonly CourseConstraint[]): void {
    Iif (this.current === undefined) return;
    this.current = { ...this.current, constraints: [...constraints] };
    this.emit('draft');
  }
 
  /** Names the course being made. */
  rename(name: string): void {
    Iif (this.current === undefined) return;
    this.current = { ...this.current, name };
    this.emit('draft');
  }
 
  /**
   * Saves the course being made as the newest course and stops making it. Returns the saved course, or `undefined`
   * when none is being made or it has no song (LR2's button 230 needs one).
   */
  finish(): CourseDefinition | undefined {
    Iif (this.current === undefined) return undefined;
    const { kind } = this.current;
    // A course saved without a name is named after its kind and its number among the courses of that kind.
    const fallback = `${UNNAMED_COURSE_LABELS[kind]} ${this.savedCourses.filter((saved) => saved.kind === kind).length + 1}`;
    const course = finishCourseDraft(
      { ...this.current, name: this.current.name.trim() || fallback },
      { defaultConnection: this.connection },
    );
    if (course === undefined) return undefined;
    this.current = undefined;
    this.savedCourses = [course, ...this.savedCourses];
    this.emit('draft');
    this.emit('courses');
    return course;
  }
 
  /** Stops making a course without saving it. */
  cancel(): void {
    Iif (this.current === undefined) return;
    this.current = undefined;
    this.emit('draft');
  }
 
  /** Steps the default NONSTOP connection (LR2's button 268). */
  stepDefaultConnection(delta: number): void {
    this.connection = stepLR2NonstopConnection(this.connection, delta);
    this.emit('settings');
  }
 
  /** Replaces the RANDOM MIX settings (each value snapped and clamped to its button's range). */
  setRandomMixSettings(settings: LR2RandomMixSettings): void {
    this.mixSettings = normalizeLR2RandomMixSettings(settings);
    this.emit('settings');
  }
 
  /** Sets the connection a new NONSTOP course gets after each stage (LR2's button 268). */
  setDefaultConnection(connection: NonstopConnection): void {
    this.connection = connection;
    this.emit('settings');
  }
 
  /** Steps one RANDOM MIX setting (LR2's buttons 260-266), wrapping around at both ends. */
  stepRandomMixSetting(key: LR2RandomMixSetting, delta: number): void {
    this.mixSettings = stepLR2RandomMixSetting(this.mixSettings, key, delta);
    this.emit('settings');
  }
 
  /**
   * Draws a RANDOM MIX course of `kind` from `charts` in `keyMode` (`drawLR2RandomMix`) and keeps it as the newest
   * course, deleting the last RANDOM MIX drawn in that folder, as LR2's `WriteRandomCourse` deletes and re-inserts its
   * `RANDOM MIX` row. The previous draw is matched as this maker's own draw rather than by its title, so a course the
   * player named "RANDOM MIX" stays. Min and max settings the wrong way round are swapped and kept so, as LR2 writes
   * them back, even when the draw then fails; a failed draw keeps the courses as they were.
   */
  drawRandomMix<T extends LR2RandomMixChart>(
    kind: 'expert' | 'nonstop',
    keyMode: number,
    charts: readonly T[],
    random: () => number,
  ): LR2RandomMixDrawResult<T> {
    // LR2 swaps the limits and writes them back before it draws, whether or not the draw finds a chart.
    const settings = resolveLR2RandomMixSettings(this.mixSettings);
    if (Object.entries(settings).some(([key, value]) => this.mixSettings[key as LR2RandomMixSetting] !== value)) {
      this.mixSettings = settings;
      this.emit('settings');
    }
    const drawn = drawLR2RandomMix({ kind, keyMode, settings, defaultConnection: this.connection }, charts, random);
    if (!drawn.ok) return drawn;
    this.keepRandomMix(drawn.course);
    return drawn;
  }
 
  /**
   * Keeps a drawn RANDOM MIX as the newest course of its kind, deleting the last RANDOM MIX drawn in that folder, as
   * LR2's `WriteRandomCourse` deletes and re-inserts its `RANDOM MIX` row. The previous draw is matched as this maker's
   * own draw rather than by its title, so a course the player named "RANDOM MIX" stays.
   */
  keepRandomMix(course: CourseDefinition): void {
    const previous = this.savedCourses.filter((saved) => saved.kind === course.kind && this.lastRandomMixes.has(saved));
    for (const saved of previous) this.lastRandomMixes.delete(saved);
    this.savedCourses = [course, ...this.savedCourses.filter((saved) => !previous.includes(saved))];
    this.lastRandomMixes.add(course);
    this.emit('courses');
  }
 
  /** Whether `course` is one of the saved courses (and so can be edited). */
  owns(course: CourseDefinition): boolean {
    return this.savedCourses.includes(course);
  }
 
  /**
   * Whether `course` is a saved course flagged for IR (`release`), and so read-only: LR2 reads a course whose `ir` is 1
   * as `courseReadOnly` (OpenLR2 L18078-L18080), and `WriteCourse` and the connection buttons refuse it (L17580-L17584,
   * L11126-L11129).
   */
  isReadOnly(course: CourseDefinition): boolean {
    return this.owns(course) && course.release;
  }
 
  /**
   * Flags a saved course for IR (LR2's button 253): sets its `release`, so its runs are ranked, and makes it read-only
   * ({@link isReadOnly}). The flag only turns on, as LR2's button does (OpenLR2 L11141-L11153). A RANDOM MIX flagged
   * becomes a course of the player's own, which the next draw keeps. Returns the flagged course, or `undefined` when
   * `course` is not a saved course or is flagged already.
   */
  releaseCourse(course: CourseDefinition): CourseDefinition | undefined {
    if (!this.owns(course) || course.release) return undefined;
    const edited = this.replace(course, { ...course, release: true });
    this.lastRandomMixes.delete(edited);
    return edited;
  }
 
  /**
   * Steps the connection after stage `slot + 1` of a saved NONSTOP course (LR2's buttons 240-248). Returns the edited
   * course, or `undefined` when `course` is not a saved NONSTOP course or is read-only.
   */
  stepConnection(course: CourseDefinition, slot: number, delta: number): CourseDefinition | undefined {
    if (!this.owns(course) || course.release || course.kind !== 'nonstop' || course.source.format !== 'lr2crs')
      return undefined;
    const current = parseLR2NonstopConnections(course.source.header)[slot] ?? 'fade';
    const edited = withNonstopConnection(course, slot, stepLR2NonstopConnection(current, delta));
    return this.replace(course, edited);
  }
 
  /**
   * Renames a saved course, read-only or not (the name does not key a course's ranking, and LR2's `ChangeCourseTitle`
   * renames an IR course too). A RANDOM MIX renamed becomes a course of the player's own, which the next draw keeps, as
   * LR2's draw only deletes the course titled `RANDOM MIX`.
   */
  renameCourse(course: CourseDefinition, name: string): CourseDefinition | undefined {
    Iif (!this.owns(course)) return undefined;
    const renamed = name.trim() || course.name;
    const edited = this.replace(course, { ...course, name: renamed });
    Eif (renamed !== LR2_RANDOM_MIX_NAME) this.lastRandomMixes.delete(edited);
    return edited;
  }
 
  /**
   * Saves a RANDOM MIX the player has played as a course of their own, named `name` (the course's name when blank): the
   * draw kept as its folder's newest course is renamed and stops being the draw the next one replaces, whatever its new
   * name; a draw that was not kept (an endless run's stages) joins the saved courses as the newest of its kind.
   */
  saveRandomMix(course: CourseDefinition, name: string): CourseDefinition {
    const named = { ...course, name: name.trim() || course.name };
    if (this.owns(course)) {
      const edited = this.replace(course, named);
      this.lastRandomMixes.delete(edited);
      return edited;
    }
    this.savedCourses = [named, ...this.savedCourses];
    this.emit('courses');
    return named;
  }
 
  /** Replaces a saved course's constraints; refused (`undefined`) for a read-only course. */
  setCourseConstraints(
    course: CourseDefinition,
    constraints: readonly CourseConstraint[],
  ): CourseDefinition | undefined {
    if (!this.owns(course) || course.release) return undefined;
    return this.replace(course, withCourseConstraints(course, constraints));
  }
 
  /** Deletes a saved course. */
  deleteCourse(course: CourseDefinition): void {
    Iif (!this.owns(course)) return;
    this.savedCourses = this.savedCourses.filter((saved) => saved !== course);
    this.lastRandomMixes.delete(course);
    this.emit('courses');
  }
 
  private replace(course: CourseDefinition, edited: CourseDefinition): CourseDefinition {
    this.savedCourses = this.savedCourses.map((saved) => (saved === course ? edited : saved));
    if (this.lastRandomMixes.delete(course)) this.lastRandomMixes.add(edited);
    this.emit('courses');
    return edited;
  }
 
  private emit(change: CourseMakerChange): void {
    this.options.onChange?.(change);
  }
}
 
/** The NEW COURSE bar of a course folder (see `LibraryCourse.newCourse`). */
export function createNewCourseEntry(kind: CourseKind): LibraryCourse {
  return {
    id: `maker:${kind}#new`,
    definition: {
      name: NEW_COURSE_NAME,
      kind,
      stages: [],
      constraints: [],
      trophies: [],
      release: false,
      source: { format: 'lr2crs', type: COURSE_MAKER_KINDS.indexOf(kind), header: '', hash: '' },
    },
    stages: [],
    playable: true,
    newCourse: true,
  };
}
 
/** The RANDOM MIX bar of an EXPERT or NONSTOP course folder (see `LibraryCourse.randomMix`). */
export function createRandomMixEntry(kind: 'expert' | 'nonstop'): LibraryCourse {
  return {
    id: `maker:${kind}#random-mix`,
    definition: {
      name: LR2_RANDOM_MIX_NAME,
      kind,
      stages: [],
      constraints: [],
      trophies: [],
      release: false,
      source: { format: 'lr2crs', type: COURSE_MAKER_KINDS.indexOf(kind), header: '', hash: '' },
    },
    stages: [],
    playable: true,
    randomMix: true,
  };
}
 
/**
 * The course folders of the player's own courses, one per course kind (EXPERT, NONSTOP, GRADE): each lists its saved
 * courses, newest first and matched to local charts, then a NEW COURSE bar, then (EXPERT and NONSTOP only) a RANDOM
 * MIX bar, as LR2's course folders do. A drawn RANDOM MIX is one of the saved courses.
 */
export function resolveCourseMakerFolders(
  courses: readonly CourseDefinition[],
  lookup: CourseChartLookup<LibraryChart>,
): LibraryFolder[] {
  return COURSE_MAKER_KINDS.map((kind) => ({
    label: COURSE_MAKER_FOLDER_LABELS[kind],
    charts: [],
    courses: [
      ...courses
        .filter((course) => course.kind === kind)
        .map((course, index) => ({
          ...resolveCourseEntry(`maker:${kind}#${index}`, course, lookup),
          editable: true as const,
        })),
      createNewCourseEntry(kind),
      ...(kind === 'grade' ? [] : [createRandomMixEntry(kind)]),
    ],
  }));
}
 
/**
 * A song as a RANDOM MIX sees it (`LR2RandomMixChart`), with the song under `chart`: its MD5, its folder (the chart's
 * directory within its source, LR2's `folder` column), key mode, play level and BPMs, the level and BPMs truncated to
 * integers as LR2's song database keeps them. A level that is not a number reads as 0.
 */
export function createRandomMixChart(
  chartEntry: LibraryChart,
  md5: string,
): LR2RandomMixChart & { readonly chart: LibraryChart } {
  const level =
    typeof chartEntry.playLevel === 'number'
      ? chartEntry.playLevel
      : Number.parseInt(String(chartEntry.playLevel ?? ''), 10);
  const slash = chartEntry.chartPath.lastIndexOf('/');
  const bpm = resolveChartBPMRange(chartEntry.chart);
  return {
    chart: chartEntry,
    md5: md5.toLowerCase(),
    folder: `${chartEntry.sourceId}/${slash < 0 ? '' : chartEntry.chartPath.slice(0, slash)}`,
    keyMode: Number(resolveLibraryChartPlayVariant(chartEntry)),
    level: Number.isFinite(level) ? Math.trunc(level) : 0,
    minBPM: Math.trunc(bpm.min),
    maxBPM: Math.trunc(bpm.max),
    title: chartEntry.title,
    ...(chartEntry.subtitle !== undefined ? { subtitle: chartEntry.subtitle } : {}),
    ...(chartEntry.artist !== undefined ? { artist: chartEntry.artist } : {}),
  };
}
 
/**
 * A library chart as the RANDOM MIX dialog and draw read it, from what the library already knows: its folder (the chart's
 * directory within its source, LR2's `folder` column), key mode, play level (truncated, 0 when it is not a number) and
 * difficulty as the library lists it (`resolveLibraryChartDifficulty`): its own `#DIFFICULTY` as `difficulty`, or an
 * estimate from its names or note count as `estimatedDifficulty`. Its BPMs and file hash are left for the charts a draw
 * walks, so building every chart's candidate stays cheap however large the library.
 */
export function createRandomMixCandidate(
  chartEntry: LibraryChart,
): RandomMixCandidate & { readonly chart: LibraryChart } {
  const level =
    typeof chartEntry.playLevel === 'number'
      ? chartEntry.playLevel
      : Number.parseInt(String(chartEntry.playLevel ?? ''), 10);
  const slash = chartEntry.chartPath.lastIndexOf('/');
  const difficulty = resolveLibraryChartDifficulty(chartEntry);
  return {
    chart: chartEntry,
    folder: `${chartEntry.sourceId}/${slash < 0 ? '' : chartEntry.chartPath.slice(0, slash)}`,
    keyMode: Number(resolveLibraryChartPlayVariant(chartEntry)),
    level: Number.isFinite(level) ? Math.trunc(level) : 0,
    ...(difficulty === undefined
      ? {}
      : difficulty.basis === 'chart'
        ? { difficulty: difficulty.value }
        : { estimatedDifficulty: difficulty.value }),
  };
}
 
/** A chart's BPMs as a RANDOM MIX reads them (`resolveChartBPMRange`, cached per chart). */
export function resolveRandomMixBPM(chartEntry: LibraryChart): { min: number; max: number } {
  return resolveChartBPMRange(chartEntry.chart);
}
 
/**
 * The course bar a RANDOM MIX draw plays: the drawn course, its stages the drawn songs, under the id its folder lists
 * it by once relisted (`resolveCourseMakerFolders`: the newest course of its kind), so the cursor comes back onto it as
 * LR2 puts it on the top bar.
 */
export function createDrawnRandomMixEntry(
  course: CourseDefinition,
  charts: readonly { readonly chart: LibraryChart }[],
): LibraryCourse {
  return {
    id: `maker:${course.kind}#0`,
    definition: course,
    stages: charts.map(({ chart }) => ({ title: chart.title, chart })),
    playable: true,
    editable: true,
  };
}