/* eslint-disable no-console */
import { mkdir, writeFile } from 'fs/promises';

import debug from 'debug';
import * as esbuild from 'esbuild';

const log = debug('webview:bundle-webview');

const result = await esbuild.build({
  entryPoints: ['src/webview-host/web-preload-builtin.ts'],
  sourcemap: false,
  write: false,
  bundle: true,
  minify: true,
});

log(
  'build result',
  result.outputFiles.map((v) => ({
    path: v.path,
    length: v.text.length,
  })),
);

const output = result.outputFiles[0].text;

const htmlWithScript = /* html */ `<!DOCTYPE html>
<html lang="en" style="width: 100%; height: 100%">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Webview Panel Container</title>
  </head>

  <body style="margin: 0; overflow: hidden; width: 100%; height: 100%"></body>
  <script>
    window.channelId = {{channelId}};
  </script>
  <script>
  ${output}
  </script>
</html>
`;

const toWrite = /* javascript */ `
/* This file is generated by scripts/bundle-webview.mjs */
/* eslint-disable */
/* prettier-ignore */
const htmlContent = ${JSON.stringify(htmlWithScript)};

export const createHTML = (channelId: string) => {
  return htmlContent.replace('{{channelId}}', JSON.stringify(channelId));
};
`.trimStart();

await writeFile('src/browser/iframe/prebuilt.ts', toWrite);

console.log('Successfully bundled webview, write to src/browser/iframe/prebuilt.ts');

if (process.env.DEBUG) {
  try {
    await mkdir('lib/prebuilt', { recursive: true });
    await writeFile('lib/prebuilt/output.js', output);
    await writeFile('lib/prebuilt/webview.html', htmlWithScript);
  } catch (error) {
    console.log('===== ~ error:', error);
  }
}
