All files / player-terminal/src/cli runner.ts

42.51% Statements 142/334
35.74% Branches 74/207
52.94% Functions 18/34
42.34% Lines 141/333

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 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069                                                                                                                                                                                                                                                                        2x 2x     3x 3x       3x   3x 3x   1x 1x 1x 1x     2x 2x 2x       2x 2x   2x             2x     3x 2x         2x   2x         2x       2x   2x 2x 2x                   2x 2x 2x                                 2x 2x           2x 2x       2x     2x 2x       2x                 2x         2x 2x 2x                     2x   2x 1x     1x 1x     1x 1x 1x 1x 1x 1x                                             1x                                                                                                                                                                                                                                                                                       3x       3x     3x     3x 3x 1x 1x 1x 1x     3x 3x 1x 1x 1x 1x     3x           3x           3x                         3x                                                                                                                                                                                                                                                                         1x 1x   1x 1x 1x             1x                             1x                   1x     1x 1x       1x     1x                                                         1x           1x 1x                     1x                                                 1x     1x 1x               1x 1x 1x 2x 2x   1x 1x               27x                                   1x     1x 1x     4x     1x     1x                                 1x 1x 1x     1x 1x   1x                         1x                                                                                     4x 3x   1x       1x 1x                                           7x           7x       1x 1x                                                                                                                                                                                   2x     2x     2x 2x               6x 3x 3x 1x   2x 2x 1x     4x 1x   3x 3x     3x 1x   2x     2x                    
import { resolveChart } from '@be-music/chart-model';
import { isCLIEntryPoint } from '@be-music/shared-utils/cli';
import { stat } from 'node:fs/promises';
import { dirname, extname, relative } from 'node:path';
import { resolveCLIPath } from '@be-music/shared-utils/cli-path';
import {
  createFileLogger,
  createNoopLogger,
  type LogEntry,
  type Logger,
  type LogLevel,
} from '@be-music/shared-utils/log';
import type { BeMusicPlayLevel } from '@be-music/chart-source';
import { parseChartFile } from '@be-music/chart-parser';
import { renderJSON, writeAudioFile } from '@be-music/chart-audio-renderer';
import {
  PlayerInterruptedError,
  type PlayerLoadProgress,
  type PlayerSummary,
  resolvePlayChart,
  type ResolvedPlayChart,
} from '@be-music/player-engine';
import { loadStageFileANSIImage, type StageFileANSIImage } from '../bga.ts';
import { runNodeGameplayRuntime } from '../node/node-gameplay-runtime.ts';
import { ensureSEAEmbeddedNodeModules } from '../node/sea-embedded-modules.ts';
import { supportsKittyGraphicsProtocol } from '../tui/kitty-graphics.ts';
import {
  resolveDisplayedJudgeRankLabel,
  resolveDisplayedJudgeRankValue,
  resolveDisplayedPlayLevelValue,
} from '@be-music/player-engine/display';
import { beginSharedRawInputCapture } from '../raw-input-capture.ts';
import {
  applyPersistedPlayerConfigToArgs,
  applyMusicSelectConfigToArgs,
  createDefaultPersistedPlayerConfig,
  loadPersistedPlayerConfig,
  normalizeHighSpeedValue,
  resolveCLIConfigOverrideFlags,
  resolveDefaultPlayerLogPath,
  resolvePersistedPlayerConfigFromArgs,
  resolvePlayModeFromArgs,
  savePersistedPlayerConfig,
  type PersistedPlayerConfig,
  type PlayMode,
} from './config.ts';
import type { ResultScreenAction, MusicSelectDifficultyFilter } from './music-select-navigation.ts';
import { truncateForDisplay } from './selection-format.ts';
import {
  buildChartSelectionEntries,
  listChartFiles,
  type ChartSelectionEntry,
  type ChartSummaryLoadingProgress,
} from './chart-selection.ts';
import { createChartFocusKey } from './music-select-state.ts';
import { type CLIArgs, parseArgs, printUsage } from './args.ts';
import {
  type RawInputCapture,
  beginLoadingAbortCapture,
  resolveLoadingCancelReason,
  applyLoadingCancel,
} from './input-capture.ts';
import {
  type PlayLoadingProgress,
  type PlayLoadingScreenRenderState,
  resolvePlayLoadingStageFileDisplaySize,
  createPlayLoadingProgressScreenOutput,
  clearPlayLoadingScreen,
  clearPlayLoadingStageFileImage,
} from './play-loading-screen.ts';
import { type PlayedChartResult, showResultScreen } from './result-screen.ts';
import {
  type SelectChartInteractivelyResult,
  sanitizeMetadataText,
  selectChartInteractively,
} from './music-select-screen.ts';
 
export {
  applyPersistedPlayerConfigToArgs,
  cyclePlayMode,
  formatPlayModeLabel,
  resolveCLIConfigOverrideFlags,
  resolveDefaultPlayerLogPath,
  resolvePersistedPlayerConfigFromArgs,
  resolvePlayModeFromArgs,
} from './config.ts';
export {
  resolveCircularSelectableIndex,
  resolvePageSelectableIndex,
  resolveResultScreenActionFromKey,
  resolveMusicSelectDifficultyFilter,
  resolveMusicSelectNavigationAction,
  resolveVisibleEntryRange,
} from './music-select-navigation.ts';
export { parseArgs } from './args.ts';
export {
  resolvePlayLoadingStageFileDisplaySize,
  createPlayLoadingProgressScreenLines,
  createPlayLoadingProgressScreenOutput,
} from './play-loading-screen.ts';
export { createMusicSelectSelectedMetadataLines, createMusicSelectControlLines } from './music-select-screen.ts';
 
type DirectorySceneState =
  | {
      kind: 'select';
      focusKey?: string;
      playMode: PlayMode;
      highSpeed: number;
      difficultyFilter?: MusicSelectDifficultyFilter;
    }
  | {
      kind: 'play';
      chartPath: string;
      focusKey?: string;
      playMode: PlayMode;
      highSpeed: number;
      difficultyFilter?: MusicSelectDifficultyFilter;
    }
  | {
      kind: 'result';
      played: PlayedChartResult;
      focusKey?: string;
      playMode: PlayMode;
      highSpeed: number;
      difficultyFilter?: MusicSelectDifficultyFilter;
    }
  | {
      kind: 'exit';
      exitCode: number;
    };
 
type ResultScreenExitAction = Exclude<ResultScreenAction, 'replay'>;
const DIRECTORY_CHART_EXTENSIONS_LABEL = '.bms, .bme, .bml, .pms, .bmson, .n2s, .lrs';
let activePlayerLogger: Logger = createNoopLogger();
 
export async function main(): Promise<void> {
  const rawArgs = process.argv.slice(2);
  Iif (rawArgs.includes('--help') || rawArgs.includes('-h')) {
    printUsage();
    return;
  }
  const overrideFlags = resolveCLIConfigOverrideFlags(rawArgs);
  let args: CLIArgs;
  try {
    args = parseArgs(rawArgs);
  } catch (error) {
    process.stdout.write(`${formatCLIParseError(error)}\n\n`);
    printUsage();
    process.exitCode = 1;
    return;
  }
 
  let persistedConfig = createDefaultPersistedPlayerConfig();
  try {
    persistedConfig = await loadPersistedPlayerConfig();
  } catch (error) {
    process.stdout.write(`Warning: failed to load ~/.be-music/player.json (${formatCLIParseError(error)}).\n`);
  }
  args = applyPersistedPlayerConfigToArgs(args, persistedConfig, overrideFlags);
  let nextPersistedConfig = resolvePersistedPlayerConfigFromArgs(args, persistedConfig);
 
  Iif (!args.input) {
    printUsage();
    process.exitCode = 1;
    return;
  }
 
  const resolvedLogFilePath =
    typeof args.logFile === 'string' && args.logFile.length > 0
      ? resolveCLIPath(args.logFile)
      : resolveDefaultPlayerLogPath();
  activePlayerLogger = await createFileLogger(resolvedLogFilePath);
  logCLI('info', 'cli.start', {
    input: args.input,
    logFile: resolvedLogFilePath,
  });
 
  try {
    // Must run before any worker spawn so the extraction directory propagates through the environment.
    await ensureSEAEmbeddedNodeModules();
  } catch (error) {
    process.stdout.write(`Warning: failed to extract embedded optional modules (${formatCLIParseError(error)}).\n`);
  }
 
  Iif (typeof args.judgeWindowMs === 'number' && Number.isFinite(args.judgeWindowMs)) {
    process.stdout.write(`Warning: debug judge override enabled (BAD window: ${Math.round(args.judgeWindowMs)}ms).\n`);
  }
 
  const inputPath = resolveCLIPath(args.input);
  let sessionInputCapture: RawInputCapture | undefined;
  try {
    const inputStat = await stat(inputPath);
    Iif (process.stdin.isTTY && process.stdout.isTTY && (inputStat.isDirectory() || args.tui)) {
      sessionInputCapture = beginSharedRawInputCapture({
        forceResetRawMode: process.platform === 'win32',
      });
      logCLI('info', 'cli.session-input-capture.started', {
        inputIsDirectory: inputStat.isDirectory(),
        tui: args.tui,
        stdinIsRaw: Boolean(sessionInputCapture.stdin.isRaw),
      });
    }
    Eif (inputStat.isDirectory()) {
      nextPersistedConfig = await runDirectoryInput(inputPath, args, nextPersistedConfig);
      return;
    }
    const action = await playSingleChartUntilExit(inputPath, dirname(inputPath), args);
    if (action === 'ctrl-c') {
      nextPersistedConfig = resolvePersistedPlayerConfigFromArgs(args, nextPersistedConfig);
      process.exitCode = 130;
      return;
    }
    nextPersistedConfig = resolvePersistedPlayerConfigFromArgs(args, nextPersistedConfig);
  } catch (error) {
    if (error instanceof PlayerInterruptedError) {
      nextPersistedConfig = resolvePersistedPlayerConfigFromArgs(args, nextPersistedConfig);
      process.exitCode = error.exitCode;
      return;
    }
    throw error;
  } finally {
    sessionInputCapture?.restore();
    Iif (sessionInputCapture) {
      logCLI('info', 'cli.session-input-capture.stopped', {
        stdinIsRaw: Boolean((process.stdin as NodeJS.ReadStream & { isRaw?: boolean }).isRaw),
      });
      sessionInputCapture = undefined;
    }
    try {
      await savePersistedPlayerConfig(nextPersistedConfig);
    } catch (error) {
      process.stdout.write(`Warning: failed to save ~/.be-music/player.json (${formatCLIParseError(error)}).\n`);
    }
    logCLI('info', 'cli.finish', {
      exitCode: process.exitCode ?? 0,
    });
    try {
      await activePlayerLogger.close();
    } catch (error) {
      process.stderr.write(`Warning: failed to close log file (${formatCLIParseError(error)}).\n`);
    }
    activePlayerLogger = createNoopLogger();
  }
}
 
async function runDirectoryInput(
  rootDir: string,
  args: CLIArgs,
  initialConfig: PersistedPlayerConfig,
): Promise<PersistedPlayerConfig> {
  let persistedConfig = persistMusicSelectConfig(initialConfig, rootDir, {
    playMode: initialConfig.playMode,
    highSpeed: initialConfig.highSpeed,
  });
  let candidates: string[];
  const startupLoadingAbortCapture = beginLoadingAbortCapture();
  try {
    candidates = await listChartFiles(rootDir, {
      signal: startupLoadingAbortCapture?.signal,
    });
  } catch (error) {
    const cancelReason = resolveLoadingCancelReason(error, startupLoadingAbortCapture);
    if (cancelReason) {
      applyLoadingCancel(cancelReason);
      return persistedConfig;
    }
    throw error;
  } finally {
    startupLoadingAbortCapture?.dispose();
  }
  if (candidates.length === 0) {
    process.stdout.write(
      `No chart files found in directory: ${rootDir} (searched for ${DIRECTORY_CHART_EXTENSIONS_LABEL})\n`,
    );
    process.exitCode = 1;
    return persistedConfig;
  }
 
  Eif (!process.stdin.isTTY || !process.stdout.isTTY) {
    const selected = candidates[0];
    process.stdout.write(`Selected chart: ${selected}\n`);
    try {
      await playChartOnce(selected, args);
      persistedConfig = persistMusicSelectConfig(resolvePersistedPlayerConfigFromArgs(args, persistedConfig), rootDir, {
        playMode: resolvePlayModeFromArgs(args),
        highSpeed: args.highSpeed,
        selectedChartFile: selected,
        focusKey: createChartFocusKey(selected),
      });
    } catch (error) {
      if (error instanceof PlayerInterruptedError) {
        persistedConfig = persistMusicSelectConfig(
          resolvePersistedPlayerConfigFromArgs(args, persistedConfig),
          rootDir,
          {
            playMode: resolvePlayModeFromArgs(args),
            highSpeed: args.highSpeed,
            selectedChartFile: selected,
            focusKey: createChartFocusKey(selected),
          },
        );
        process.exitCode = error.exitCode;
        return persistedConfig;
      }
      throw error;
    }
    return persistedConfig;
  }
 
  if (candidates.length === 1) {
    const selected = candidates[0];
    process.stdout.write(`Selected chart: ${selected}\n`);
    try {
      const action = await playSingleChartUntilExit(selected, rootDir, args);
      persistedConfig = persistMusicSelectConfig(resolvePersistedPlayerConfigFromArgs(args, persistedConfig), rootDir, {
        playMode: resolvePlayModeFromArgs(args),
        highSpeed: args.highSpeed,
        selectedChartFile: selected,
        focusKey: createChartFocusKey(selected),
      });
      if (action === 'ctrl-c') {
        process.exitCode = 130;
      }
    } catch (error) {
      if (error instanceof PlayerInterruptedError) {
        persistedConfig = persistMusicSelectConfig(
          resolvePersistedPlayerConfigFromArgs(args, persistedConfig),
          rootDir,
          {
            playMode: resolvePlayModeFromArgs(args),
            highSpeed: args.highSpeed,
            selectedChartFile: selected,
            focusKey: createChartFocusKey(selected),
          },
        );
        process.exitCode = error.exitCode;
        return persistedConfig;
      }
      throw error;
    }
    return persistedConfig;
  }
 
  const entries = await loadChartSelectionEntries(rootDir, candidates);
  if (!entries) {
    return persistedConfig;
  }
 
  let state: DirectorySceneState = {
    kind: 'select',
    focusKey: resolveMusicSelectInitialFocusKey(
      candidates,
      resolveLastSelectedChartFileForDirectory(initialConfig, rootDir),
      resolveLastMusicSelectFocusKeyForDirectory(initialConfig, rootDir),
    ),
    playMode: persistedConfig.playMode,
    highSpeed: persistedConfig.highSpeed,
    difficultyFilter: undefined,
  };
 
  while (state.kind !== 'exit') {
    if (state.kind === 'select') {
      const selection = await selectChartInteractively(rootDir, candidates, {
        audio: args.audio,
        kittyGraphics: args.kittyGraphics,
        imageResizeAlgorithm: args.imageResizeAlgorithm,
        volume: args.volume,
        bgmVolume: args.bgmVolume,
        playVolume: args.playVolume,
        entries,
        initialFocusKey: state.focusKey,
        initialPlayMode: state.playMode,
        initialHighSpeed: state.highSpeed,
        initialDifficultyFilter: state.difficultyFilter,
      });
      persistedConfig = persistMusicSelectConfig(persistedConfig, rootDir, {
        playMode: selection.playMode,
        highSpeed: selection.highSpeed,
        selectedChartFile: resolveLastSelectedChartFile(selection),
        focusKey: selection.focusKey,
      });
      state = resolveDirectoryStateFromSelection(selection);
      continue;
    }
 
    if (state.kind === 'play') {
      const playState = state;
      const playArgs = applyMusicSelectConfigToArgs(args, playState.playMode, playState.highSpeed);
      persistedConfig = persistMusicSelectConfig(persistedConfig, rootDir, {
        playMode: playState.playMode,
        highSpeed: playArgs.highSpeed,
        selectedChartFile: playState.chartPath,
        focusKey: playState.focusKey,
      });
      try {
        const played = await playChartOnce(playState.chartPath, playArgs);
        const resolvedHighSpeed = normalizeHighSpeedValue(playArgs.highSpeed);
        persistedConfig = persistMusicSelectConfig(persistedConfig, rootDir, {
          playMode: playState.playMode,
          highSpeed: resolvedHighSpeed,
          selectedChartFile: playState.chartPath,
          focusKey: playState.focusKey,
        });
        state = {
          kind: 'result',
          played,
          focusKey: playState.focusKey,
          playMode: playState.playMode,
          highSpeed: resolvedHighSpeed,
          difficultyFilter: playState.difficultyFilter,
        };
      } catch (error) {
        if (error instanceof PlayerInterruptedError) {
          const resolvedHighSpeed = normalizeHighSpeedValue(playArgs.highSpeed);
          persistedConfig = persistMusicSelectConfig(persistedConfig, rootDir, {
            playMode: playState.playMode,
            highSpeed: resolvedHighSpeed,
            selectedChartFile: playState.chartPath,
            focusKey: playState.focusKey,
          });
          state = resolveDirectoryStateFromPlayInterrupt(error.reason, {
            ...playState,
            highSpeed: resolvedHighSpeed,
          });
          continue;
        }
        throw error;
      }
      continue;
    }
 
    const resultAction = await showResultScreen(rootDir, state.played);
    state = resolveDirectoryStateFromResultAction(resultAction, state);
  }
 
  process.exitCode = state.exitCode;
  return persistedConfig;
}
 
function resolvePersistedConfigForMusicSelect(
  base: Pick<PersistedPlayerConfig, 'playMode' | 'highSpeed'>,
  directoryPath: string | undefined,
  preferredLastSelectedChartFile?: string,
  preferredFocusKey?: string,
  previous?: PersistedPlayerConfig,
): PersistedPlayerConfig {
  const resolved: PersistedPlayerConfig = {
    playMode: base.playMode,
    highSpeed: normalizeHighSpeedValue(base.highSpeed),
  };
  Iif (previous?.lastSelectedChartFileByDirectory) {
    resolved.lastSelectedChartFileByDirectory = { ...previous.lastSelectedChartFileByDirectory };
  }
  Iif (previous?.lastMusicSelectFocusKeyByDirectory) {
    resolved.lastMusicSelectFocusKeyByDirectory = { ...previous.lastMusicSelectFocusKeyByDirectory };
  }
  const preferred = preferredLastSelectedChartFile?.trim();
  if (preferred) {
    Eif (directoryPath && directoryPath.length > 0) {
      const byDirectory = { ...resolved.lastSelectedChartFileByDirectory };
      byDirectory[directoryPath] = preferred;
      resolved.lastSelectedChartFileByDirectory = byDirectory;
    }
  }
  const normalizedFocusKey = preferredFocusKey?.trim();
  if (normalizedFocusKey) {
    Eif (directoryPath && directoryPath.length > 0) {
      const byDirectory = { ...resolved.lastMusicSelectFocusKeyByDirectory };
      byDirectory[directoryPath] = normalizedFocusKey;
      resolved.lastMusicSelectFocusKeyByDirectory = byDirectory;
    }
  }
  Iif (
    resolved.lastSelectedChartFileByDirectory &&
    Object.keys(resolved.lastSelectedChartFileByDirectory).length === 0
  ) {
    delete resolved.lastSelectedChartFileByDirectory;
  }
  Iif (
    resolved.lastMusicSelectFocusKeyByDirectory &&
    Object.keys(resolved.lastMusicSelectFocusKeyByDirectory).length === 0
  ) {
    delete resolved.lastMusicSelectFocusKeyByDirectory;
  }
  return resolved;
}
 
function persistMusicSelectConfig(
  previous: PersistedPlayerConfig,
  directoryPath: string | undefined,
  state: {
    playMode: PlayMode;
    highSpeed: number | undefined;
    selectedChartFile?: string;
    focusKey?: string;
  },
): PersistedPlayerConfig {
  return resolvePersistedConfigForMusicSelect(
    {
      playMode: state.playMode,
      highSpeed: normalizeHighSpeedValue(state.highSpeed),
    },
    directoryPath,
    state.selectedChartFile,
    state.focusKey,
    previous,
  );
}
 
function resolveLastSelectedChartFile(selection: SelectChartInteractivelyResult): string | undefined {
  if (typeof selection.selectedPath === 'string' && selection.selectedPath.length > 0) {
    return selection.selectedPath;
  }
  return resolveChartFileFromFocusKey(selection.focusKey);
}
 
function resolveLastSelectedChartFileForDirectory(
  config: PersistedPlayerConfig,
  directoryPath: string,
): string | undefined {
  const byDirectory = config.lastSelectedChartFileByDirectory;
  if (byDirectory) {
    const scoped = byDirectory[directoryPath];
    if (typeof scoped === 'string' && scoped.trim().length > 0) {
      return scoped;
    }
  }
  return undefined;
}
 
function resolveLastMusicSelectFocusKeyForDirectory(
  config: PersistedPlayerConfig,
  directoryPath: string,
): string | undefined {
  const byDirectory = config.lastMusicSelectFocusKeyByDirectory;
  if (byDirectory) {
    const scoped = byDirectory[directoryPath];
    if (typeof scoped === 'string' && scoped.trim().length > 0) {
      return scoped;
    }
  }
  return undefined;
}
 
function resolveDirectoryStateFromSelection(selection: SelectChartInteractivelyResult): DirectorySceneState {
  if (selection.reason === 'ctrl-c') {
    return {
      kind: 'exit',
      exitCode: 130,
    };
  }
 
  if (selection.reason === 'escape' || !selection.selectedPath) {
    return {
      kind: 'exit',
      exitCode: 0,
    };
  }
 
  return {
    kind: 'play',
    chartPath: selection.selectedPath,
    focusKey: selection.focusKey,
    playMode: selection.playMode,
    highSpeed: selection.highSpeed,
    difficultyFilter: selection.difficultyFilter,
  };
}
 
function resolveDirectoryStateFromPlayInterrupt(
  reason: PlayerInterruptedError['reason'],
  state: Extract<DirectorySceneState, { kind: 'play' }>,
): DirectorySceneState {
  if (reason === 'restart') {
    return {
      kind: 'play',
      chartPath: state.chartPath,
      focusKey: state.focusKey,
      playMode: state.playMode,
      highSpeed: state.highSpeed,
      difficultyFilter: state.difficultyFilter,
    };
  }
  if (reason === 'escape') {
    return {
      kind: 'select',
      focusKey: state.focusKey,
      playMode: state.playMode,
      highSpeed: state.highSpeed,
      difficultyFilter: state.difficultyFilter,
    };
  }
  return {
    kind: 'exit',
    exitCode: 130,
  };
}
 
function resolveDirectoryStateFromResultAction(
  action: ResultScreenAction,
  state: Extract<DirectorySceneState, { kind: 'result' }>,
): DirectorySceneState {
  if (action === 'replay') {
    return {
      kind: 'play',
      chartPath: state.played.chartPath,
      focusKey: state.focusKey,
      playMode: state.playMode,
      highSpeed: state.highSpeed,
      difficultyFilter: state.difficultyFilter,
    };
  }
 
  if (action === 'enter' || action === 'escape') {
    return {
      kind: 'select',
      focusKey: state.focusKey,
      playMode: state.playMode,
      highSpeed: state.highSpeed,
      difficultyFilter: state.difficultyFilter,
    };
  }
 
  return {
    kind: 'exit',
    exitCode: action === 'ctrl-c' ? 130 : 0,
  };
}
 
async function playChartOnce(chartPath: string, args: CLIArgs): Promise<PlayedChartResult> {
  let resolvedHighSpeed = normalizeHighSpeedValue(args.highSpeed);
  const effectivePlayMode = resolveEffectivePlayModeFromCLIArgs(args);
  let playLoadingStageFileImage: StageFileANSIImage | undefined;
  const stageFileKittySupported = supportsKittyGraphicsProtocol(process.env);
  const useKittyGraphicsForStageFile = args.kittyGraphics && Boolean(process.stdout.isTTY) && stageFileKittySupported;
  logCLI('info', 'play.loading.stagefile.mode', {
    chartPath,
    kittyGraphicsRequested: Boolean(args.kittyGraphics),
    stdoutIsTTY: Boolean(process.stdout.isTTY),
    kittyGraphicsSupported: stageFileKittySupported,
    useKittyGraphicsForStageFile,
  });
  const playLoadingScreenRenderState: PlayLoadingScreenRenderState = {
    initialized: false,
    stageFileDrawn: false,
    stageFileKittyVisible: false,
  };
  let resolvedChartMetadata:
    | {
        title?: string;
        artist?: string;
        player?: number;
        rank: number;
        rankLabel?: string;
        playLevel?: BeMusicPlayLevel;
      }
    | undefined;
  const reportPlayLoadingProgress = process.stdout.isTTY
    ? (progress: PlayLoadingProgress): void => {
        renderPlayLoadingProgress(chartPath, progress, {
          columns: process.stdout.columns,
          stageFileImage: playLoadingStageFileImage,
          useKittyGraphics: useKittyGraphicsForStageFile,
          state: playLoadingScreenRenderState,
        });
      }
    : undefined;
  const chartLoadingAbortCapture = beginLoadingAbortCapture();
  let json: Awaited<ReturnType<typeof parseChartFile>>;
  let playChart: ResolvedPlayChart;
  try {
    reportPlayLoadingProgress?.({
      ratio: 0.03,
      message: 'Parsing chart file...',
    });
    json = await parseChartFile(chartPath, {
      signal: chartLoadingAbortCapture?.signal,
    });
    Iif (process.stdout.isTTY && typeof json.metadata.stageFile === 'string' && json.metadata.stageFile.length > 0) {
      reportPlayLoadingProgress?.({
        ratio: 0.12,
        message: 'Loading stage image...',
        detail: json.metadata.stageFile.replaceAll('\\', '/'),
      });
      const stageFileDisplaySize = resolvePlayLoadingStageFileDisplaySize(process.stdout.columns, process.stdout.rows);
      playLoadingStageFileImage = await loadStageFileANSIImage(json, {
        baseDir: dirname(chartPath),
        width: stageFileDisplaySize.width,
        height: stageFileDisplaySize.height,
        imageResizeAlgorithm: args.imageResizeAlgorithm,
        signal: chartLoadingAbortCapture?.signal,
      });
      logCLI('info', 'play.loading.stagefile.loaded', {
        chartPath,
        stageFile: json.metadata.stageFile.replaceAll('\\', '/'),
        requestedWidth: stageFileDisplaySize.width,
        requestedHeight: stageFileDisplaySize.height,
        loaded: Boolean(playLoadingStageFileImage),
        width: playLoadingStageFileImage?.width,
        height: playLoadingStageFileImage?.height,
        hasKittyImage: Boolean(playLoadingStageFileImage?.kittyImage),
        kittyCellWidth: playLoadingStageFileImage?.kittyImage?.cellWidth,
        kittyCellHeight: playLoadingStageFileImage?.kittyImage?.cellHeight,
        kittyPixelWidth: playLoadingStageFileImage?.kittyImage?.pixelWidth,
        kittyPixelHeight: playLoadingStageFileImage?.kittyImage?.pixelHeight,
      });
    }
    reportPlayLoadingProgress?.({
      ratio: 0.16,
      message: 'Chart parsed.',
    });
    // Resolve `#RANDOM` / `#SWITCH` once here, so the preview render and the play below use the same branches and
    // the engine never draws on its own. A restart draws again (LR2 / beatoraja re-roll each play).
    playChart = resolvePlayChart(json);
    for (const { message, position } of resolveChart(playChart.chart, {
      chartPath,
      inferBmsLNTypeWhenMissing: args.inferBmsLNTypeWhenMissing,
    }).diagnostics) {
      const location =
        position.kind === 'field'
          ? position.path
          : `#${String(position.measure).padStart(3, '0')}${position.channel} ${position.position.join('/')}`;
      process.stderr.write(`${chartPath}: ${location}: ${message}\n`);
    }
 
    Iif (args.renderAudioPath) {
      reportPlayLoadingProgress?.({
        ratio: 0.2,
        message: 'Rendering preview audio...',
      });
      const outputPath = resolveCLIPath(args.renderAudioPath);
      const audioRendered = await renderJSON(playChart.chart, {
        baseDir: dirname(chartPath),
        inferBmsLNTypeWhenMissing: args.inferBmsLNTypeWhenMissing,
        signal: chartLoadingAbortCapture?.signal,
      });
      await writeAudioFile(outputPath, audioRendered);
      process.stdout.write(`Rendered preview audio: ${outputPath}\n`);
      reportPlayLoadingProgress?.({
        ratio: 0.32,
        message: 'Preview audio rendered.',
      });
    }
  } catch (error) {
    const cancelReason = resolveLoadingCancelReason(error, chartLoadingAbortCapture);
    if (cancelReason) {
      throw new PlayerInterruptedError(cancelReason);
    }
    throw error;
  } finally {
    chartLoadingAbortCapture?.dispose();
  }
 
  const playOptions = createPlayOptionsFromCLIArgs(args, chartPath);
  logCLI('info', 'play.start', {
    chartPath,
    mode: effectivePlayMode,
    kittyGraphics: args.kittyGraphics,
    videoBGAStreaming: args.videoBGAStreaming,
  });
 
  let summary: PlayerSummary;
  while (true) {
    let playbackLoadingAbortCapture = beginLoadingAbortCapture();
    const disposePlaybackLoadingAbortCapture = (): void => {
      playbackLoadingAbortCapture?.dispose();
      playbackLoadingAbortCapture = undefined;
    };
    try {
      summary = await runNodeGameplayRuntime({
        json: playChart.chart,
        randomDraws: playChart.randomDraws,
        mode: effectivePlayMode === 'auto' ? 'auto' : 'manual',
        autoScratch: effectivePlayMode === 'auto-scratch',
        playOptions,
        signal: playbackLoadingAbortCapture?.signal,
        writeOutput: (text: string): void => {
          process.stdout.write(text);
        },
        onHighSpeedChange: (value: number): void => {
          resolvedHighSpeed = normalizeHighSpeedValue(value);
        },
        onLoadProgress: reportPlayLoadingProgress
          ? (progress: PlayerLoadProgress): void => {
              const mappedRatio = 0.22 + Math.max(0, Math.min(1, progress.ratio)) * 0.76;
              reportPlayLoadingProgress({
                ratio: mappedRatio,
                message: progress.message,
                detail: progress.detail,
                audioStatus: progress.audioStatus,
                graphicsStatus: progress.graphicsStatus,
              });
            }
          : undefined,
        onLoadComplete: () => {
          logCLI('info', 'play.loading.complete', {
            chartPath,
          });
          clearPlayLoadingScreen(playLoadingScreenRenderState);
          disposePlaybackLoadingAbortCapture();
        },
        onLog: (entry) => {
          activePlayerLogger.log(entry);
        },
        onResolvedChart: (metadata) => {
          resolvedChartMetadata = metadata;
        },
      });
      break;
    } catch (error) {
      const cancelReason = resolveLoadingCancelReason(error, playbackLoadingAbortCapture);
      if (cancelReason) {
        throw new PlayerInterruptedError(cancelReason);
      }
      if (error instanceof PlayerInterruptedError && error.reason === 'restart') {
        playChart = resolvePlayChart(json);
        playLoadingScreenRenderState.stageFileDrawn = false;
        reportPlayLoadingProgress?.({
          ratio: 0.34,
          message: 'Restarting playback...',
        });
        continue;
      }
      throw error;
    } finally {
      clearPlayLoadingStageFileImage(playLoadingScreenRenderState);
      disposePlaybackLoadingAbortCapture();
      args.highSpeed = resolvedHighSpeed;
    }
  }
  const title = sanitizeMetadataText(json.metadata.title);
  const artist = sanitizeMetadataText(json.metadata.artist);
 
  return {
    chartPath,
    summary,
    title: sanitizeMetadataText(resolvedChartMetadata?.title) ?? title,
    artist: sanitizeMetadataText(resolvedChartMetadata?.artist) ?? artist,
    player: resolvedChartMetadata?.player ?? json.bms.player,
    rank: resolvedChartMetadata?.rank ?? resolveDisplayedJudgeRankValue(json),
    rankLabel: resolvedChartMetadata?.rankLabel ?? resolveDisplayedJudgeRankLabel(json),
    playLevel: resolvedChartMetadata?.playLevel ?? resolveDisplayedPlayLevelValue(json),
  };
}
 
function createPlayOptionsFromCLIArgs(args: CLIArgs, chartPath: string) {
  return {
    inferBmsLNTypeWhenMissing: args.inferBmsLNTypeWhenMissing,
    showInvisibleNotes: args.showInvisibleNotes,
    compressor: args.compressor,
    compressorThresholdDb: args.compressorThresholdDb,
    compressorRatio: args.compressorRatio,
    compressorAttackMs: args.compressorAttackMs,
    compressorReleaseMs: args.compressorReleaseMs,
    compressorMakeupDb: args.compressorMakeupDb,
    limiter: args.limiter,
    limiterCeilingDb: args.limiterCeilingDb,
    limiterReleaseMs: args.limiterReleaseMs,
    speed: args.speed,
    uiFPS: args.uiFPS,
    tuiVisibleNotesLimit: args.tuiVisibleNotesLimit,
    tuiNoteHeight: args.tuiNoteHeight,
    imageResizeAlgorithm: args.imageResizeAlgorithm,
    highSpeed: args.highSpeed,
    judgeWindowMs: args.judgeWindowMs,
    bmsonTotalMode: args.bmsonTotalMode,
    judgeRuleset: args.judgeRuleset,
    gauge: args.gauge,
    endOnFailure: args.endOnFailure,
    debugActiveAudio: args.debugActiveAudio,
    audio: args.audio,
    volume: args.volume,
    bgmVolume: args.bgmVolume,
    playVolume: args.playVolume,
    audioBaseDir: dirname(chartPath),
    audioTailSeconds: args.audioTailSeconds,
    audioHeadPaddingMs: args.audioHeadPaddingMs,
    audioLeadMs: args.audioLeadMs,
    audioLeadMaxMs: args.audioLeadMaxMs,
    audioLeadStepUpMs: args.audioLeadStepUpMs,
    audioLeadStepDownMs: args.audioLeadStepDownMs,
    laneModeExtension: resolveChartLaneModeExtension(chartPath),
    tui: args.tui,
    kittyGraphics: args.kittyGraphics,
    videoBGAStreaming: args.videoBGAStreaming,
  };
}
 
export function resolveEffectivePlayModeFromCLIArgs(args: Pick<CLIArgs, 'auto' | 'autoScratch' | 'tui'>): PlayMode {
  if (!args.tui) {
    return 'auto';
  }
  return resolvePlayModeFromArgs(args);
}
 
function resolveChartLaneModeExtension(chartPath: string): string | undefined {
  const extension = extname(chartPath).toLowerCase();
  return extension.length > 0 ? extension : undefined;
}
 
async function playSingleChartUntilExit(
  chartPath: string,
  rootDir: string,
  args: CLIArgs,
): Promise<ResultScreenExitAction> {
  while (true) {
    const played = await playChartOnce(chartPath, args);
    const action = await showResultScreen(rootDir, played, {
      allowReplay: true,
      nextActionLabel: 'exit player',
    });
    if (action === 'replay') {
      continue;
    }
    return action;
  }
}
 
function logCLI(level: LogLevel, event: string, fields?: Record<string, unknown>): void {
  const entry: LogEntry = {
    source: 'cli',
    level,
    event,
    fields,
  };
  activePlayerLogger.log(entry);
}
 
function formatCLIParseError(error: unknown): string {
  Eif (error instanceof Error && error.message) {
    return error.message;
  }
  return 'Failed to parse CLI arguments';
}
 
async function loadChartSelectionEntries(rootDir: string, files: string[]): Promise<ChartSelectionEntry[] | undefined> {
  const loadingAbortCapture = beginLoadingAbortCapture();
  process.stdout.write('\u001b[?25l');
 
  try {
    const entries = await buildChartSelectionEntries(rootDir, files, {
      onLoadingFile: (progress) => {
        renderChartLoadingProgress(rootDir, progress);
      },
      signal: loadingAbortCapture?.signal,
    });
    return entries;
  } catch (error) {
    const cancelReason = resolveLoadingCancelReason(error, loadingAbortCapture);
    if (cancelReason) {
      applyLoadingCancel(cancelReason);
      return undefined;
    }
    throw error;
  } finally {
    loadingAbortCapture?.dispose();
    process.stdout.write('\u001b[?25h');
  }
}
 
function renderChartLoadingProgress(rootDir: string, progress: ChartSummaryLoadingProgress): void {
  const columns = process.stdout.columns ?? 80;
  const lineWidth = Math.max(16, columns - 2);
  const relativePath = relative(rootDir, progress.filePath).replaceAll('\\', '/');
  const ratio = progress.totalCount > 0 ? progress.currentIndex / progress.totalCount : 0;
  const barWidth = Math.max(10, Math.min(48, lineWidth - 8));
  const filled = Math.max(0, Math.min(barWidth, Math.round(barWidth * ratio)));
  const bar = `[${'#'.repeat(filled)}${'-'.repeat(barWidth - filled)}] ${Math.round(ratio * 100)}%`;
  const lines = [
    `Loading charts... (${progress.currentIndex}/${progress.totalCount})`,
    truncateForDisplay(bar, lineWidth),
    truncateForDisplay(`Loading: ${relativePath}`, lineWidth),
    '',
    'Press Ctrl+C or Esc to exit.',
  ];
  process.stdout.write(`\u001b[2J\u001b[H${lines.join('\n')}\u001b[J`);
}
 
function renderPlayLoadingProgress(
  chartPath: string,
  progress: PlayLoadingProgress,
  options: {
    columns?: number;
    stageFileImage?: StageFileANSIImage;
    useKittyGraphics?: boolean;
    state: PlayLoadingScreenRenderState;
  },
): void {
  const shouldRedrawStageFile = Boolean(options.stageFileImage) && !options.state.stageFileDrawn;
  const shouldResetScreen = !options.state.initialized || shouldRedrawStageFile;
  const output = createPlayLoadingProgressScreenOutput(chartPath, progress, {
    columns: options.columns,
    stageFileImage: options.stageFileImage,
    useKittyGraphics: options.useKittyGraphics,
    resetScreen: shouldResetScreen,
    includeStageFileImage: shouldRedrawStageFile,
  });
  if (options.state.lastOutput === output) {
    return;
  }
  if (shouldRedrawStageFile && options.stageFileImage && !options.state.stageFileRenderLogged) {
    logCLI('info', 'play.loading.stagefile.render', {
      useKittyGraphics: options.useKittyGraphics === true && options.stageFileImage.kittyImage !== undefined,
      width: options.stageFileImage.width,
      height: options.stageFileImage.height,
      hasKittyImage: Boolean(options.stageFileImage.kittyImage),
    });
    options.state.stageFileRenderLogged = true;
  }
  process.stdout.write(output);
  options.state.initialized = true;
  options.state.lastOutput = output;
  if (options.stageFileImage) {
    options.state.stageFileDrawn = true;
    options.state.stageFileKittyVisible =
      options.useKittyGraphics === true && options.stageFileImage.kittyImage !== undefined;
  }
}
 
function resolveChartFileFromFocusKey(focusKey: string | undefined): string | undefined {
  Iif (typeof focusKey !== 'string') {
    return undefined;
  }
  Iif (!focusKey.startsWith('chart:')) {
    return undefined;
  }
  const filePath = focusKey.slice('chart:'.length).trim();
  return filePath.length > 0 ? filePath : undefined;
}
 
export function resolveMusicSelectInitialFocusKey(
  files: readonly string[],
  selectedChartFile: string | undefined,
  persistedFocusKey?: string,
): string | undefined {
  if (typeof persistedFocusKey === 'string') {
    const normalizedFocusKey = persistedFocusKey.trim();
    if (normalizedFocusKey === 'random') {
      return normalizedFocusKey;
    }
    const focusedChartFile = resolveChartFileFromFocusKey(normalizedFocusKey);
    if (focusedChartFile && files.includes(focusedChartFile)) {
      return normalizedFocusKey;
    }
  }
  if (typeof selectedChartFile !== 'string') {
    return undefined;
  }
  const normalized = selectedChartFile.trim();
  Iif (normalized.length === 0) {
    return undefined;
  }
  if (!files.includes(normalized)) {
    return undefined;
  }
  return createChartFocusKey(normalized);
}
 
Iif (isCLIEntryPoint(() => (import.meta as { url?: unknown }).url)) {
  void main()
    .then(() => {
      process.exit(process.exitCode ?? 0);
    })
    .catch((error) => {
      process.stderr.write(`${formatCLIParseError(error)}\n`);
      process.exit(1);
    });
}