// SPDX-FileCopyrightText: 2026 FocusFlow contributors
// SPDX-License-Identifier: AGPL-3.0-only

/// Runs the Test workspace script.
library;

import 'dart:io';

/// Runs tests, combines coverage, enforces coverage, and checks Dart docs.
Future<void> main(List<String> arguments) async {
  await _deleteCoverageDirectory();
  await _run('dart', <String>['pub', 'global', 'activate', 'coverage']);
  await _run('dart', <String>['test', '--coverage=coverage']);
  await _run('dart', <String>[
    'pub',
    'global',
    'run',
    'coverage:format_coverage',
    '--lcov',
    '--in=coverage',
    '--out=coverage/lcov.info',
    '--packages=.dart_tool/package_config.json',
    '--report-on=packages',
  ]);
  await _run('dart', <String>[
    'run',
    'tool/check_coverage.dart',
    'coverage/lcov.info',
    '80',
  ]);
  await _run('dart', <String>['run', 'tool/check_reuse.dart']);
  await _run('dart', <String>['run', 'tool/check_docs.dart']);
}

/// Top-level helper that performs the `_deleteCoverageDirectory` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
Future<void> _deleteCoverageDirectory() async {
  final coverage = Directory('coverage');
  if (await coverage.exists()) {
    await coverage.delete(recursive: true);
  }
}

/// Top-level helper that performs the `_run` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
Future<void> _run(String executable, List<String> arguments) async {
  final command = '$executable ${arguments.join(' ')}';
  stdout.writeln('> $command');
  final result = await Process.run(
    executable,
    arguments,
    runInShell: Platform.isWindows,
  );
  stdout.write(result.stdout);
  stderr.write(result.stderr);
  if (result.exitCode != 0) {
    throw ProcessException(
      executable,
      arguments,
      'Command failed with exit code ${result.exitCode}.',
      result.exitCode,
    );
  }
}
