import fs from 'fs';
import path from 'path';

// Import shared types
import Config from '../types/Config';

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

// Get project directory
const currDir = (process.env.PWD || process.env.CWD);

/* eslint-disable no-console */

// Check if the current directory is an NPM project
const configFilename = path.join(currDir, 'dceConfig.json');
if (!fs.existsSync(configFilename)) {
  // Initialize npm project
  print.title('DCE Configuration Not Found');
  console.log('');
  console.log('Create dceConfig.json and populate it with deployments:');
  console.log('{');
  console.log('  "deployments": [');
  console.log('    {');
  console.log('      "name": "Stage",');
  console.log('      "app": "mytool-stage",');
  console.log('      "profile": "stage"');
  console.log('    },');
  console.log('    {');
  console.log('      "name": "Prod",');
  console.log('      "service": "mytool",');
  console.log('      "profile": "prod"');
  console.log('    }');
  console.log('  ]');
  console.log('}');
  console.log('');
  console.log('Where "name" is a human-readable name, "app" is the name of the deployment service, and "profile" is the name of the aws profile you use to access it.');
  console.log('');
  process.exit(0);
}

// Get the name of the current project
const config: Config = JSON.parse(fs.readFileSync(configFilename, 'utf-8'));
const { deployments } = config;
if (!deployments || deployments.length === 0) {
  console.log('Oops! Your /config/dceConfig.json is not fully configured. Add a "deployments" array.');
  process.exit(0);
}
for (let i = 0; i < deployments.length; i++) {
  if (!deployments[i].name || !deployments[i].app || !deployments[i].profile) {
    console.log('Oops! Each deployment must have a "name", "app", and "profile"');
    process.exit(0);
  }
}

/**
 * Configuration file, parsed as a JSON object
 * @author Gabe Abrams
 */
export default config;
