/**
 * Generates the browser extension's injected page scripts from their canonical implementations:
 *
 * - `public/devtools-hook.js` from `__qwik_install_hook_runtime__`
 * - `public/vnode-bridge.js` from `__qwik_install_vnode_runtime__`
 *
 * Both live once in `packages/devtools/plugin/src/runtime/` and are shared with the Vite plugin
 * (SSR middleware / virtual module). This script keeps the extension copies in sync.
 *
 * Runs automatically as the first step of the `build` and `dev` scripts.
 */
import { existsSync, writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const here = dirname(fileURLToPath(import.meta.url));

// Internal build artifact of @qwik.dev/devtools (not a published subpath), imported
// by relative path. Requires the devtools package to be built first.
const codegenPath = resolve(here, '..', '..', 'devtools', 'dist', 'plugin', 'codegen.mjs');
if (!existsSync(codegenPath)) {
  console.error(
    `[gen-injected-scripts] missing ${codegenPath}\n` +
      'Build the devtools package first (pnpm --filter @qwik.dev/devtools build).'
  );
  process.exit(1);
}

const publicDir = resolve(here, '..', 'public');
const { createExtensionHookRuntime, createVNodeRuntime } = await import(codegenPath);

const VNODE_BANNER =
  '// GENERATED by scripts/gen-injected-scripts.mjs from\n' +
  '// packages/devtools/plugin/src/runtime/installers.ts (__qwik_install_vnode_runtime__).\n' +
  '// Do not edit by hand.\n';

const outputs = [
  { file: 'devtools-hook.js', source: createExtensionHookRuntime() },
  { file: 'vnode-bridge.js', source: VNODE_BANNER + createVNodeRuntime() },
];

for (const { file, source } of outputs) {
  const outPath = resolve(publicDir, file);
  writeFileSync(outPath, source);
  console.log(`[gen-injected-scripts] wrote ${outPath}`);
}
