"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPackageFile = extractPackageFile;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const logger_1 = require("../../../logger");
const upgradeable_tooling_1 = require("./upgradeable-tooling");
const utils_1 = require("./utils");
function extractPackageFile(content, packageFile) {
    logger_1.logger.trace(`mise.extractPackageFile(${packageFile})`);
    const misefile = (0, utils_1.parseTomlFile)(content, packageFile);
    if (!misefile) {
        return null;
    }
    const deps = [];
    const tools = misefile.tools;
    if (tools) {
        for (const [name, toolData] of Object.entries(tools)) {
            const version = parseVersion(toolData);
            const depName = name.trim();
            const toolConfig = getToolConfig(depName, version);
            const dep = createDependency(depName, version, toolConfig);
            deps.push(dep);
        }
    }
    return deps.length ? { deps } : null;
}
function parseVersion(toolData) {
    if (is_1.default.nonEmptyString(toolData)) {
        // Handle the string case
        // e.g. 'erlang = "23.3"'
        return toolData;
    }
    if (is_1.default.array(toolData, is_1.default.string)) {
        // Handle the array case
        // e.g. 'erlang = ["23.3", "24.0"]'
        return toolData.length ? toolData[0] : null; // Get the first version in the array
    }
    if (is_1.default.nonEmptyString(toolData.version)) {
        // Handle the object case with a string version
        // e.g. 'python = { version = "3.11.2" }'
        return toolData.version;
    }
    return null; // Return null if no version is found
}
function getToolConfig(name, version) {
    if (version === null) {
        return null; // Early return if version is null
    }
    // Try to get the config from miseTooling first, then asdfTooling
    return (getConfigFromTooling(upgradeable_tooling_1.miseTooling, name, version) ??
        getConfigFromTooling(upgradeable_tooling_1.asdfTooling, name, version));
}
function getConfigFromTooling(toolingSource, name, version) {
    const toolDefinition = toolingSource[name];
    if (!toolDefinition) {
        return null;
    } // Return null if no toolDefinition is found
    return ((typeof toolDefinition.config === 'function'
        ? toolDefinition.config(version)
        : toolDefinition.config) ?? null); // Ensure null is returned instead of undefined
}
function createDependency(name, version, config) {
    if (version === null) {
        return { depName: name, skipReason: 'unspecified-version' };
    }
    if (config === null) {
        return { depName: name, skipReason: 'unsupported-datasource' };
    }
    return {
        depName: name,
        currentValue: version,
        ...config,
    };
}
//# sourceMappingURL=extract.js.map