/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import esbuild from 'esbuild';
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';

mkdirSync('dist/client', { recursive: true });

await esbuild.build({
  entryPoints: ['client/src/main.tsx'],
  bundle: true,
  minify: true,
  format: 'esm',
  target: 'es2020',
  jsx: 'automatic',
  outfile: 'dist/client/main.js',
  define: {
    'process.env.NODE_ENV': '"production"',
  },
});

// Embed client assets as string constants so the devtools server can be
// bundled into the CLI without needing readFileSync + __dirname at runtime.
const indexHtml = readFileSync('client/index.html', 'utf-8');
const clientJs = readFileSync('dist/client/main.js', 'utf-8');

writeFileSync(
  'src/_client-assets.ts',
  `/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Auto-generated by esbuild.client.js — do not edit\nexport const INDEX_HTML = ${JSON.stringify(indexHtml)};\nexport const CLIENT_JS = ${JSON.stringify(clientJs)};\n`,
);
