import fs from 'node:fs/promises';
import path from 'node:path';

const projectRoot = process.cwd();
const packageJsonPath = path.join(projectRoot, 'package.json');
const configuredDistPath = process.env.WORK_SERVER_DIST_DIR?.trim() || 'dist';
const distDirectoryPath = path.resolve(projectRoot, configuredDistPath);
const buildInfoPath = path.join(distDirectoryPath, 'build-info.json');
const distNodeModulesPath = path.join(distDirectoryPath, 'node_modules');
const projectNodeModulesPath = path.join(projectRoot, 'node_modules');

const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));
const builtAt = new Date().toISOString();

const buildInfo = {
  version: typeof packageJson.version === 'string' ? packageJson.version : '0.0.0',
  buildId: `${typeof packageJson.version === 'string' ? packageJson.version : '0.0.0'}@${builtAt}`,
  builtAt,
};

await fs.mkdir(distDirectoryPath, { recursive: true });
await fs.writeFile(buildInfoPath, JSON.stringify(buildInfo, null, 2));

try {
  const existingNodeModulesLink = await fs.lstat(distNodeModulesPath);
  if (existingNodeModulesLink.isSymbolicLink()) {
    await fs.unlink(distNodeModulesPath);
  }
} catch (error) {
  if (error?.code !== 'ENOENT') {
    throw error;
  }
}

try {
  await fs.symlink(projectNodeModulesPath, distNodeModulesPath, 'dir');
} catch (error) {
  if (error?.code !== 'EEXIST') {
    throw error;
  }
}

console.log(`work-server build info written to ${buildInfoPath}`);
