const fs = require('fs');
const path = require('path');

const rootDir = path.resolve(__dirname, '..');
const serverPackageJsonPath = path.join(rootDir, 'server', 'package.json');
const outputFilePath = path.join(rootDir, 'server', 'src', 'generated', 'build-version.ts');

function readServerVersion() {
  const packageJson = JSON.parse(fs.readFileSync(serverPackageJsonPath, 'utf8'));

  if (typeof packageJson.version === 'string' && packageJson.version.trim().length > 0) {
    return packageJson.version.trim();
  }

  return '0.0.0';
}

function syncServerBuildVersion(version = readServerVersion()) {
  const nextContents = `export const SERVER_BUILD_VERSION = ${JSON.stringify(version)};\n`;

  fs.mkdirSync(path.dirname(outputFilePath), { recursive: true });

  if (!fs.existsSync(outputFilePath) || fs.readFileSync(outputFilePath, 'utf8') !== nextContents) {
    fs.writeFileSync(outputFilePath, nextContents, 'utf8');
  }

  return version;
}

function main() {
  const version = syncServerBuildVersion();

  console.log(`[server-build-version] Synced ${outputFilePath} -> ${version}`);
}

if (require.main === module) {
  try {
    main();
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);

    console.error(`[server-build-version] ${message}`);
    process.exitCode = 1;
  }
}

module.exports = {
  syncServerBuildVersion
};
