"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFfiLib = exports.PACT_FFI_VERSION = void 0;
const node_path_1 = __importDefault(require("node:path"));
const bindings = require("node-gyp-build");
const detect_libc_1 = require("detect-libc");
const logger_1 = __importStar(require("../logger"));
const types_1 = require("./types");
exports.PACT_FFI_VERSION = '0.4.22';
function getPlatformArchSpecificPackage() {
    const { arch } = process;
    let os = process.platform;
    if (['win32', 'cygwin'].includes(process.platform)) {
        os = 'windows';
    }
    let platformArchSpecificPackage = `@you54f/pact-core-${os}-${arch}`;
    if (os === 'linux') {
        platformArchSpecificPackage += (0, detect_libc_1.isNonGlibcLinuxSync)() ? '-musl' : '-glibc';
    }
    const prebuildPackageLocation = process.env['PACT_PREBUILD_PACKAGE_LOCATION'];
    if (prebuildPackageLocation) {
        platformArchSpecificPackage = node_path_1.default.join(prebuildPackageLocation, platformArchSpecificPackage);
    }
    const packagePath = `${platformArchSpecificPackage}/package.json`;
    try {
        require.resolve(packagePath);
        return platformArchSpecificPackage;
    }
    catch (e) {
        throw new Error(`Couldn't find npm package ${platformArchSpecificPackage} \n 💡 you can tell Pact where the npm package is located with env var $PACT_PREBUILD_PACKAGE_LOCATION`);
    }
}
const supportedPlatforms = [
    'darwin-arm64',
    'darwin-x64',
    'linux-arm64',
    'linux-x64',
    'win32-x64',
];
const platform = `${process.platform}-${process.arch}`;
const supportedPlatformsMessage = [
    'Supported platforms are: ',
    ` - ${supportedPlatforms.join('\n - ')}`,
].join('\n');
const detectedMessage = `We detected your platform as: \n\n - ${platform}`;
logger_1.default.debug(detectedMessage);
if (!supportedPlatforms.includes(platform)) {
    logger_1.default.warn(supportedPlatformsMessage);
    logger_1.default.warn(detectedMessage);
    logger_1.default.error(`Unsupported platform: ${platform}`);
    throw new Error(`Unsupported platform: ${platform}`);
}
const loadPathMessage = (bindingsPath) => `: attempting to load native module from: \n\n - ${node_path_1.default.join(bindingsPath, 'prebuilds', platform)} ${process.env['PACT_PREBUILD_LOCATION']
    ? `\n - source: PACT_PREBUILD_LOCATION \n - You must have a supported prebuild for your platform at this location in the path ${node_path_1.default.join(process.env['PACT_PREBUILD_LOCATION'], 'prebuilds', platform)}`
    : `\n   source: pact-js-core binding lookup \n\n - You can override via PACT_PREBUILD_LOCATION\n`}`;
const bindingsResolver = (bindingsPath) => bindings(bindingsPath);
const bindingPaths = [
    node_path_1.default.resolve(__dirname, '..', '..', 'node_modules', getPlatformArchSpecificPackage()),
    node_path_1.default.resolve(__dirname, '..', '..'),
    process.env['PACT_PREBUILD_LOCATION']?.toString() ?? node_path_1.default.resolve(),
];
let ffiLib;
const renderBinaryErrorMessage = (error) => {
    logger_1.default.debug(supportedPlatformsMessage);
    logger_1.default.error(`Failed to find native module for ${platform}: ${error}`);
    bindingPaths.forEach((bindingPath) => {
        logger_1.default.debug(`We looked for a supported build in this location ${node_path_1.default.join(bindingPath ?? node_path_1.default.resolve(), 'prebuilds', platform)}`);
    });
    logger_1.default.debug(`Tip: check there is a prebuild for ${platform} \n
          check the path exists\n
      Wrong Path?: set the load path with PACT_PREBUILD_LOCATION ensuring that ${node_path_1.default.join('$PACT_PREBUILD_LOCATION', 'prebuilds', platform)} exists\n
      - Note: You dont need to include the prebuilds/${platform} part of the path, just the parent directory\n
      - Let us know: We can add more supported path lookups easily, chat to us on slack or raise an issue on github`);
};
let ffi;
const initialiseFfi = () => {
    if (process.stdout._handle) {
        process.stdout._handle.setBlocking(true);
    }
    try {
        bindingPaths.every((bindingPath, i) => {
            try {
                logger_1.default.debug(`binding path #${i}: ${loadPathMessage(bindingPath)}`);
                ffiLib = bindingsResolver(bindingPath);
                if (ffiLib.pactffiVersion() === exports.PACT_FFI_VERSION) {
                    logger_1.default.info('pact native library successfully found, and the correct version', ffiLib.pactffiVersion());
                    return false;
                }
                return true;
            }
            catch (error) {
                return true;
            }
        });
    }
    catch (error) {
        renderBinaryErrorMessage(error);
        throw new Error(`Failed to load native module, try setting LOG_LEVEL=debug for more info`);
    }
    return ffiLib;
};
const getFfiLib = (logLevel = logger_1.DEFAULT_LOG_LEVEL, logFile = undefined) => {
    if (!ffi) {
        logger_1.default.trace('Initialising ffi for the first time');
        ffi = initialiseFfi();
        logger_1.default.debug(`Initialising native core at log level '${logLevel}'`, logFile);
        if (logFile) {
            logger_1.default.debug(`writing log file at level ${logLevel} to ${logFile}`);
            const res = ffiLib.pactffiLogToFile(logFile, types_1.FfiLogLevelFilter[logLevel] ?? 3);
            if (res !== 0) {
                logger_1.default.warn(`Failed to write log file to ${logFile}, reason: ${res}`);
            }
        }
        else {
            ffiLib.pactffiInitWithLogLevel(logLevel);
        }
    }
    return ffi;
};
exports.getFfiLib = getFfiLib;
//# sourceMappingURL=index.js.map