'use strict';

const path = require('path');
const { execSync } = require('child_process');

const PKG_DIR = path.resolve(__dirname, '..');
const CURRENT_VERSION = require(path.join(PKG_DIR, 'package.json')).version;
const PACKAGE_NAME = require(path.join(PKG_DIR, 'package.json')).name;

async function checkForUpdate() {
  try {
    const latest = execSync(`npm view ${PACKAGE_NAME} version`, {
      encoding: 'utf8',
      timeout: 5000,
      stdio: ['ignore', 'pipe', 'ignore'],
    }).trim();
    if (!latest) return null;
    if (!isNewer(latest, CURRENT_VERSION)) return null;
    return { version: latest, tag: `v${latest}` };
  } catch {
    return null;
  }
}

async function notifyIfUpdateAvailable() {
  try {
    const update = await checkForUpdate();
    if (update) {
      process.stderr.write(
        `\nUpdate available: ${CURRENT_VERSION} → ${update.version}\n` +
        `Run: npm update -g ${PACKAGE_NAME}\n\n`,
      );
    }
  } catch {
    // Silent
  }
}

function isNewer(a, b) {
  const normalize = (v) => v.replace(/^v/, '').split('-')[0].split('.').map(Number);
  const pa = normalize(a);
  const pb = normalize(b);
  for (let i = 0; i < 3; i++) {
    if ((pa[i] || 0) > (pb[i] || 0)) return true;
    if ((pa[i] || 0) < (pb[i] || 0)) return false;
  }
  const aPrerelease = a.includes('-');
  const bPrerelease = b.includes('-');
  if (!aPrerelease && bPrerelease) return true;
  return false;
}

module.exports = {
  CURRENT_VERSION,
  checkForUpdate,
  notifyIfUpdateAvailable,
};
