import { defineConfig } from 'vitest/config';
import { availableParallelism } from 'node:os';

// Default vitest's pool to ~half the CPU threads we have. The previous
// implicit default left this 64-thread workstation at ~10% utilization
// during `pnpm test:run`. Half is a soft cap that stays kind to laptops
// (8-thread → 4 workers) while letting beefy hosts push closer to the
// box's actual capacity. Override at run time with VITEST_MAX_THREADS.
const cores = availableParallelism();
const maxThreads = Number(process.env['VITEST_MAX_THREADS'] ?? Math.max(2, Math.floor(cores / 2)));

export default defineConfig({
  test: {
    globals: true,
    pool: 'threads',
    poolOptions: {
      threads: { maxThreads, minThreads: 1 },
    },
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
      exclude: ['**/node_modules/**', '**/dist/**', '**/*.config.*'],
    },
    include: ['src/*/tests/**/*.test.ts', 'tests/**/*.test.ts'],
    // src/web tests need jsdom; they're run via the web package's own
    // vitest.config.ts under the projects entry below.
    exclude: ['**/node_modules/**', '**/smoke/**', 'src/db/tests/**', 'src/web/tests/**'],
    testTimeout: 10000,
    // Vitest 4 uses `projects` (in-config) instead of vitest.workspace.ts.
    // Each project below is rooted in a workspace package; vitest reads
    // its `vitest.config.ts` (or vite.config.ts) for the test config.
    projects: [
      'src/shared',
      'src/cli',
      'src/mcpd',
      'src/mcplocal',
      'src/web',
    ],
    // DB tests require a test database; run them explicitly via:
    //   pnpm --filter db exec vitest run
    // globalSetup: ['src/db/tests/global-setup.ts'],
  },
});
