const fs = require('fs');
const path = require('path');
const { syncServerBuildVersion } = require('./sync-server-build-version.js');

const rootDir = path.resolve(__dirname, '..');
const packageJsonPaths = [
  path.join(rootDir, 'package.json'),
  path.join(rootDir, 'server', 'package.json')
];

function parseArgs(argv) {
  const args = {};

  for (let index = 0; index < argv.length; index += 1) {
    const token = argv[index];

    if (!token.startsWith('--')) {
      continue;
    }

    const key = token.slice(2);
    const nextToken = argv[index + 1];

    if (!nextToken || nextToken.startsWith('--')) {
      args[key] = true;
      continue;
    }

    args[key] = nextToken;
    index += 1;
  }

  return args;
}

function normalizeVersion(rawValue) {
  if (typeof rawValue !== 'string') {
    return null;
  }

  const trimmedValue = rawValue.trim();

  if (!trimmedValue) {
    return null;
  }

  const normalized = trimmedValue.replace(/^v/i, '').split('+')[0] || null;

  return normalized && /^(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/.test(normalized)
    ? normalized
    : null;
}

function updatePackageJson(filePath, version) {
  const packageJson = JSON.parse(fs.readFileSync(filePath, 'utf8'));
  packageJson.version = version;
  fs.writeFileSync(filePath, `${JSON.stringify(packageJson, null, 2)}\n`, 'utf8');
}

function main() {
  const args = parseArgs(process.argv.slice(2));
  const version = normalizeVersion(args.version || process.env.RELEASE_VERSION);

  if (!version) {
    throw new Error('A valid semver release version is required. Pass it with --version.');
  }

  for (const packageJsonPath of packageJsonPaths) {
    updatePackageJson(packageJsonPath, version);
  }

  syncServerBuildVersion(version);
  console.log(`[release-version] Updated package versions to ${version}`);
}

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

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