import { Ajv } from 'ajv';
import { EMULSIFY_PROJECT_CONFIG_FILE } from '../../lib/constants.js';
import findFileInCurrentPath from '../fs/findFileInCurrentPath.js';
import loadJsonFile from '../fs/loadJsonFile.js';
let validateProjectConfig;
async function getProjectConfigValidator() {
    if (!validateProjectConfig) {
        const [{ default: projectConfigSchema }, { default: variantSchema }] = await Promise.all([
            import('../../schemas/emulsifyProjectConfig.json', {
                with: { type: 'json' },
            }),
            import('../../schemas/variant.json', { with: { type: 'json' } }),
        ]);
        const ajv = new Ajv({ allErrors: true });
        ajv.addSchema(variantSchema, 'variant.json');
        validateProjectConfig = ajv.compile(projectConfigSchema);
    }
    return validateProjectConfig;
}
function formatProjectConfigError(error) {
    const location = error.instancePath || '/';
    return `${location} ${error.message}`;
}
async function validateEmulsifyConfig(config, path) {
    const validate = await getProjectConfigValidator();
    if (!validate(config)) {
        const errors = (validate.errors || [])
            .map(formatProjectConfigError)
            .join('; ');
        throw new Error(`Invalid Emulsify project configuration in "${path}": ${errors}`);
    }
    return config;
}
export default async function getEmulsifyConfig() {
    const path = findFileInCurrentPath(EMULSIFY_PROJECT_CONFIG_FILE);
    if (!path) {
        return undefined;
    }
    const config = await loadJsonFile(path);
    if (config === undefined) {
        return undefined;
    }
    return validateEmulsifyConfig(config, path);
}
