import { execSync } from 'node:child_process';
import { resolve, dirname, relative } from 'node:path';
import { fileURLToPath } from 'node:url';

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

function run(cmd, cwd = root) {
  console.log(`\n> ${cmd}  (${relative(root, cwd) || '.'})`)
  execSync(cmd, { cwd, stdio: 'inherit' });
}

console.log('=== Step 1: Clean ===');
run('npm run clean');

console.log('\n=== Step 2: Build CLI ===');
run('npm run build');

console.log('\n=== Step 3: Build Web (2 targets) ===');
const webDir = resolve(root, 'clients/web');
run('npm run build', webDir);
run('npm run build:vscode', webDir);

console.log('\n=== Step 4: VS Code Extension ===');
const vscodeDir = resolve(root, 'clients/vscode');
run('npm run dist', vscodeDir);

console.log('\n=== Step 5: Build Office (2 targets) ===');
const officeDir = resolve(root, 'clients/office');
run('npm run build', officeDir);
run('npm run build:desktop', officeDir);

console.log('\n=== Step 6: Build Browser ===');
run('npm run build', resolve(root, 'clients/browser'));

console.log('\n=== Step 7: Package Desktop ===');
const desktopDir = resolve(root, 'clients/desktop');
const packageCmd = process.platform === 'win32' ? 'npm run package:win' : 'npm run package:mac';
run(packageCmd, desktopDir);

console.log('\n=== Step 8: Install VS Code Extension ===');
const codeCmd = process.platform === 'win32' ? 'code.cmd' : 'code';
run(`${codeCmd} --install-extension dist/clients/extension.vsix`);

console.log('\nDone.');
