import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import { execSync } from 'node:child_process';

const rootDir = process.cwd();
const createDir = path.join(rootDir, 'create-swdg');
const swdgDir = path.join(rootDir, 'swdg');

const createPkgPath = path.join(createDir, 'package.json');
const swdgPkgPath = path.join(swdgDir, 'package.json');

const input = process.argv[2];
if (!input) {
  console.error('Usage: node scripts/release.mjs <x.y.z>');
  process.exit(1);
}

const readJson = (filePath) => JSON.parse(fs.readFileSync(filePath, 'utf8'));
const writeJson = (filePath, data) =>
  fs.writeFileSync(filePath, JSON.stringify(data, null, 2) + '\n', 'utf8');

const isValidVersion = (value) => /^\d+\.\d+\.\d+$/.test(value);
const createPkg = readJson(createPkgPath);
const swdgPkg = readJson(swdgPkgPath);

if (!isValidVersion(input)) {
  console.error('Version must be in x.y.z format, e.g. 0.1.2');
  process.exit(1);
}

const nextVersion = input;

createPkg.version = nextVersion;
swdgPkg.version = nextVersion;
swdgPkg.dependencies = swdgPkg.dependencies || {};
swdgPkg.dependencies['create-swdg-frontend'] = `^${nextVersion}`;

writeJson(createPkgPath, createPkg);
writeJson(swdgPkgPath, swdgPkg);

try {
  execSync('npm config set registry https://registry.npmjs.org/', {
    stdio: 'inherit',
  });
  execSync('pnpm -C create-swdg run prepublishOnly', { stdio: 'inherit' });
  execSync('npm publish --access public --registry https://registry.npmjs.org/', {
    stdio: 'inherit',
    cwd: createDir,
  });
  execSync('npm publish --access public --registry https://registry.npmjs.org/', {
    stdio: 'inherit',
    cwd: swdgDir,
  });
} finally {
  execSync('npm config set registry https://registry.npmmirror.com/', {
    stdio: 'inherit',
  });
}
