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

// Get current working directory
let currDir = (process.env.PWD || process.env.CWD);

// Remove part after node_modules if it exists
if (currDir.includes('/node_modules')) {
  currDir = currDir.split('/node_modules')[0];
}

/**
 * Get the major version of Node.js from a Dockerfile.
 * @author Gabe Abrams
 * @returns major version of Node.js (e.g. 22) or null if not found
 */
const getMajorNodeVersionInDockerfile = async (): Promise<number | null> => {
  const dockerfilePath = path.join(currDir, 'Dockerfile');
  const dockerfileContents = fs.readFileSync(dockerfilePath, 'utf8');
  const nodeVersionRegex = /FROM\s+node:(\d+)/;
  const nodeMajorVersionMatch = dockerfileContents.match(nodeVersionRegex);
  const nodeMajorVersion = (
    nodeMajorVersionMatch
      ? Number.parseInt(nodeMajorVersionMatch[1], 10)
      : null
  );
  return nodeMajorVersion;
};

export default getMajorNodeVersionInDockerfile;
