// NOTICE: This file is generated by Rollup. To modify it,
// please instead edit the ESM counterpart and rebuild with Rollup (npm run build).
'use strict';

const fs = require('node:fs');
const path = require('node:path');
const dynamicImport = require('./dynamicImport.cjs');
const index = require('../formatters/index.cjs');
const getFormatterOptionsText = require('./getFormatterOptionsText.cjs');
const resolveOptionValue = require('./resolveOptionValue.cjs');

/** @import {Formatter, FormatterType, InternalApi} from 'stylelint' */

/**
 * @param {InternalApi} stylelint
 * @returns {Promise<Formatter>}
 */
async function getFormatter(stylelint) {
	/** @type {FormatterType | undefined} */
	let formatter = await resolveOptionValue({ stylelint, name: 'formatter' });

	if (typeof formatter === 'string') {
		let formatterFunction = index[formatter];

		if (formatterFunction === undefined) {
			if (fs.existsSync(formatter)) {
				formatterFunction = await dynamicImport(path.resolve(formatter)).then((m) => m.default);
			} else {
				const formattersText = getFormatterOptionsText(', ', '"');

				throw new Error(`You must use a valid formatter option: ${formattersText} or a function`);
			}
		}

		return formatterFunction;
	}

	// Assume a function or a promise of a function.
	if (typeof formatter === 'function' || formatter) {
		return Promise.resolve(formatter);
	}

	formatter ??= stylelint._options._defaultFormatter ?? 'json';

	return index[formatter];
}

module.exports = getFormatter;
