"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const cosmiconfig_1 = require("cosmiconfig");
const deepmerge_1 = tslib_1.__importDefault(require("deepmerge"));
const node_fetch_1 = tslib_1.__importDefault(require("node-fetch"));
const path = tslib_1.__importStar(require("path"));
const release_1 = require("./release");
const try_require_1 = tslib_1.__importDefault(require("./utils/try-require"));
function normalizeLabel(name, label) {
    const baseLabel = (release_1.defaultLabelDefinition[name] || [{}])[0];
    if (typeof label === 'string') {
        return [Object.assign(Object.assign({}, baseLabel), { name: label })];
    }
    if (Array.isArray(label)) {
        return label
            .map(l => normalizeLabel(name, l))
            .reduce((acc, item) => [...acc, ...item], []);
    }
    if (!label.name) {
        label.name = name;
    }
    return [Object.assign(Object.assign({}, baseLabel), label)];
}
exports.normalizeLabel = normalizeLabel;
function normalizeLabels(config) {
    let labels = release_1.defaultLabelDefinition;
    if (config.labels) {
        const definitions = Object.entries(config.labels).map(([label, labelDef]) => ({
            [label]: normalizeLabel(label, labelDef)
        }));
        labels = deepmerge_1.default.all([labels, ...definitions], {
            arrayMerge: (destinationArray, sourceArray) => sourceArray
        });
    }
    return labels;
}
exports.normalizeLabels = normalizeLabels;
class Config {
    constructor(logger) {
        this.logger = logger;
    }
    /**
     * Load the .autorc from the file system, set up defaults, combine with CLI args
     * load the extends property, load the plugins and start the git remote interface.
     */
    async loadConfig(args) {
        const explorer = cosmiconfig_1.cosmiconfig('auto', {
            searchPlaces: [
                `.autorc`,
                `.autorc.json`,
                `.autorc.yaml`,
                `.autorc.yml`,
                'package.json'
            ]
        });
        const result = await explorer.search();
        let rawConfig = {};
        if (result && result.config) {
            rawConfig = result.config;
        }
        if (rawConfig.extends) {
            rawConfig = deepmerge_1.default(rawConfig, await this.loadExtendConfig(rawConfig.extends));
        }
        const labels = normalizeLabels(rawConfig);
        const semVerLabels = release_1.getVersionMap(labels);
        this.logger.verbose.success('Using SEMVER labels:', '\n', semVerLabels);
        const skipReleaseLabels = rawConfig.skipReleaseLabels || [];
        if (!skipReleaseLabels.includes(semVerLabels.get('skip-release'))) {
            (semVerLabels.get('skip-release') || []).map(l => skipReleaseLabels.push(l));
        }
        return Object.assign(Object.assign(Object.assign({}, rawConfig), args), { labels,
            skipReleaseLabels });
    }
    /**
     * Loads a config from a path, package name, or special `auto-config` pattern
     *
     * ex: auto-config-MY_CONFIG
     * ex: @MY_CONFIG/auto-config
     *
     * @param extend Path or name of config to find
     */
    async loadExtendConfig(extend) {
        let config;
        if (extend.endsWith('.js') || extend.endsWith('.mjs')) {
            throw new Error('Extended config cannot be a JavaScript file');
        }
        if (extend.startsWith('http')) {
            try {
                config = (await node_fetch_1.default(extend)).json();
                this.logger.verbose.note(`${extend} found: ${config}`);
            }
            catch (error) {
                error.message = `Failed to get extended config from ${extend} -- ${error.message}`;
                throw error;
            }
        }
        else if (extend.startsWith('.')) {
            config = try_require_1.default(extend);
            if (extend.endsWith('package.json')) {
                config = config && config.auto;
            }
            this.logger.verbose.note(`${extend} found: ${config}`);
        }
        else {
            config = try_require_1.default(`${extend}/package.json`);
            config = config && config.auto;
            this.logger.verbose.note(`${extend} found: ${config}`);
        }
        if (!config) {
            const scope = `${extend}/auto-config/package.json`;
            config = try_require_1.default(scope);
            config = config && config.auto;
            this.logger.verbose.note(`${scope} found: ${config}`);
        }
        if (!config) {
            const scope = `auto-config-${extend}/package.json`;
            config = try_require_1.default(scope);
            config = config && config.auto;
            this.logger.verbose.note(`${scope} found: ${config}`);
        }
        if (!config) {
            config = try_require_1.default(path.join(process.cwd(), extend));
        }
        if (!config) {
            throw new Error(`Unable to load extended config ${extend}`);
        }
        return config;
    }
}
exports.default = Config;
//# sourceMappingURL=config.js.map