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

const level = process.argv[2] || '--patch';

// Read the current version from package.json
const packageJsonPath = path.join(process.cwd(), 'package.json');
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
const currentVersion = packageJson.version;
let [major, minor, patchWithSuffix] = currentVersion.split('.');
let [patch, ...suffixParts] = patchWithSuffix.match(/(\d+)([^\d].*)?/).slice(1);
const suffix = suffixParts.join('') || '';

switch (level) {
  case '--patch':
    patch = Number(patch) + 1;
    break;
  case '--minor':
    minor = Number(minor) + 1;
    patch = 0;
    break;
  case '--major':
    major = Number(major) + 1;
    minor = 0;
    patch = 0;
    break;
  default:
    throw new Error(`Invalid level: ${level}`);
}

try {
  const newVersion = `${[major, minor, patch].join('.')}${suffix}`;

  packageJson.version = newVersion;

  fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));

  // Login to npm
  if (process.env.NPM_USERNAME && process.env.NPM_PASSWORD) {
    execSync(
      `{ echo ${process.env.NPM_USERNAME}; sleep 1; echo ${process.env.NPM_PASSWORD}; } | yarn npm login --scope=coinweb`,
      { stdio: 'inherit' }
    );
  } else {
    throw new Error('NPM_USERNAME and NPM_PASSWORD are not set');
  }

  // Publish the package to npm with the hash-tagged version
  execSync(`npm publish`, { stdio: 'inherit' });

  // biome-ignore lint/suspicious/noConsoleLog: cli tool
  console.log(`Package published with version: ${newVersion}`);
} catch (error) {
  console.error('Failed to publish package:');
  console.error(error.message);

  // RESTORE the original version in package.json
  packageJson.version = currentVersion;
  fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
}
