import { execSync } from 'node:child_process';
import { mkdirSync } from 'node:fs';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { bundleOmegaEntrypoints } from '../../scripts/omega-esbuild.mjs';

const __dirname = dirname(fileURLToPath(import.meta.url));
const dist = resolve(__dirname, 'dist');

// Don't rmSync dist/ — concurrent turbo tasks may be reading from it.
// esbuild and tsc overwrite files in place.
mkdirSync(dist, { recursive: true });

// 1. esbuild: bundle src/index.ts → dist/index.js (self-contained, all deps inlined)
await bundleOmegaEntrypoints({
  cwd: __dirname,
  entryPoints: ['src/index.ts'],
  platform: 'node',
  target: 'node20',
  outfile: 'dist/index.js',
});

// 2. esbuild: bundle src/index.browser.ts → dist/index.browser.js (no SystemIOBackend)
await bundleOmegaEntrypoints({
  cwd: __dirname,
  entryPoints: ['src/index.browser.ts'],
  platform: 'browser',
  target: 'es2022',
  outfile: 'dist/index.browser.js',
});

// 3. tsc: emit declarations only (mirrors structure for .d.ts)
// --skipLibCheck: the broad tsconfig includes the entire omega tree;
// some files import @open-matrix/inference which resolves at the parent
// project level but not here in isolation. Our exported types are correct.
execSync('npx tsc -p tsconfig.json --emitDeclarationOnly --skipLibCheck', { cwd: __dirname, stdio: 'inherit' });

console.log('@open-matrix/omega-core built → dist/index.js + dist/index.browser.js + .d.ts');
