"use strict";
/* eslint-disable @typescript-eslint/no-explicit-any */
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const path = tslib_1.__importStar(require("path"));
const try_require_1 = tslib_1.__importDefault(require("./try-require"));
/** Require a plugin and log where it was found. */
function requirePlugin(pluginPath, logger) {
    const plugin = try_require_1.default(pluginPath);
    if (plugin) {
        logger.verbose.info(`Found plugin using: ${pluginPath}`);
    }
    return plugin;
}
/** Try to load a plugin in various ways */
function loadPlugin([pluginPath, options], logger) {
    let plugin;
    // Try requiring a path
    if (pluginPath.startsWith('.') || pluginPath.startsWith('/')) {
        plugin = requirePlugin(pluginPath, logger);
    }
    // Try requiring a path from cwd
    if (!plugin && (pluginPath.startsWith('.') || pluginPath.startsWith('/'))) {
        const localPath = path.join(process.cwd(), pluginPath);
        plugin = requirePlugin(localPath, logger);
        if (!plugin) {
            logger.log.warn(`Could not find plugin from path: ${localPath}`);
            return;
        }
    }
    // For pkg bundle
    if (!plugin) {
        const pkgPath = path.join(__dirname, '../../../../../plugins/', pluginPath, 'dist/index.js');
        plugin = requirePlugin(pkgPath, logger);
    }
    // For a user created plugin
    if (!plugin) {
        plugin = requirePlugin(`auto-plugin-${pluginPath}`, logger);
    }
    // Try importing official plugin
    if (!plugin) {
        plugin = requirePlugin(path.join('@auto-it', pluginPath), logger);
    }
    if (!plugin) {
        logger.log.warn(`Could not find plugin: ${pluginPath}`);
        return;
    }
    try {
        if ('default' in plugin && plugin.default) {
            // eslint-disable-next-line new-cap
            return new plugin.default(options);
        }
        return new plugin(options);
    }
    catch (error) {
        logger.log.error(`Plugin at the following path encountered an error: ${pluginPath}`);
        throw error;
    }
}
exports.default = loadPlugin;
//# sourceMappingURL=load-plugins.js.map