import path from 'path';

// Import shared helpers
import print from './helpers/print';
import exec from './helpers/exec';
import getPackageJSON from './helpers/getPackageJSON';

// Get current working directory
const wizardPackageJSON = getPackageJSON(path.join(__dirname, '../package.json'));

/*----------------------------------------*/
/* ---------------- Main ---------------- */
/*----------------------------------------*/

/**
 * Validate that the user is running the most up-to-date version of the dev wizard
 * @author Gabe Abrams
 */
const validateWizardVersion = () => {
  // Get latest wizard version
  const latestWizardVersionString = exec(`npm view dce-dev-wizard versions --json | jq -r '.[] | select(test("-beta") | not)' | sort -rV | head -n 1`);
  const latestWizardVersion = latestWizardVersionString.trim();

  // Get current wizard version
  const currentWizardVersion = wizardPackageJSON.version;

  // If versions don't match, show warning
  if (latestWizardVersion !== currentWizardVersion) {
    print.title('Wizard Out of Date');
    console.log('');
    console.error(`You are running version ${currentWizardVersion} of the dev wizard.`);
    console.error(`The latest version of the dev wizard is ${latestWizardVersion}.`);
    console.log('');
    console.log('Upgrade and try again:');
    console.log(`npm i --save-dev dce-dev-wizard@${latestWizardVersion}`);
    process.exit(0);
  }
};

export default validateWizardVersion;
