'use strict';

const platform = process.platform;
const { sep } = require('path');
const { version: packageVersion } = require('./package.json');
const { GLIBC, MUSL, familySync, versionSync } = require('detect-libc');

let bindingsPath = () => {

  switch (platform) {
    case 'linux': {
      const family = familySync();
      switch (family) {
        case GLIBC: {
          const glibcVersion = versionSync();
          if (glibcVersion) {
            const [major, minor] = glibcVersion.split('.');
            if (major < 2 || (major == 2 && minor < 17)) {
              throw new Error(`Unsupported glibc version.  Only version 2.17.0 or above is supported.  Detected version ${glibcVersion}`);
            }
          }
          return `${__dirname}${sep}contrast.${platform}-${process.arch}-gnu.node`;
        }
        case MUSL: {
          return `${__dirname}${sep}contrast.${platform}-${process.arch}-musl.node`;
        }
        default: {
          throw new Error(`Unsupported glibc family. ${family} is not supported.`);
        }
      }
    }
    case 'win32': {
      return `${__dirname}${sep}contrast.${platform}-${process.arch}-msvc.node`;
    }
    case 'darwin': {
      return `${__dirname}${sep}contrast.${platform}-${process.arch}.node`;
    }
    default: {
      throw new Error(`Unsupported platform.  ${platform} is not supported.`);
    }
  }
}

try {
  /**
   * @type {import('./index').AgentLib}
   */
  const lib = require(`${bindingsPath()}`);
  lib.version = packageVersion;

  module.exports = {
    ...lib, // to support CommonJS
    default: lib  // to also support ES6/TypeScript modules
  }
}
catch (e) {
  console.error(e);
  throw e;
}