import { pathExists } from 'fs-extra';
import { dirname } from 'path';
import { EMULSIFY_PROJECT_CONFIG_FILE } from '../../lib/constants.js';
import findFileInCurrentPath from '../fs/findFileInCurrentPath.js';
import safeResolveWithin from '../fs/safeResolveWithin.js';
import copyItemFromCache from '../cache/copyItemFromCache.js';
export function getComponentDestination(variant, componentName, projectConfigPath) {
    const component = variant.components.find(({ name }) => name === componentName);
    if (!component) {
        throw new Error(`The specified component (${componentName}) does not exist within the given system variant.`);
    }
    const structure = variant.structureImplementations.find(({ name }) => name === component.structure);
    if (!structure) {
        throw new Error(`The structure (${component.structure}) specified within the component ${componentName} is invalid.`);
    }
    return safeResolveWithin(dirname(projectConfigPath), [structure.directory, component.name], 'Component destination');
}
export default async function installComponentFromCache(system, variant, componentName, force = false) {
    const path = findFileInCurrentPath(EMULSIFY_PROJECT_CONFIG_FILE);
    if (!path) {
        throw new Error('Unable to find an Emulsify project to install the component into.');
    }
    const destination = getComponentDestination(variant, componentName, path);
    const component = variant.components.find(({ name }) => name === componentName);
    const structure = variant.structureImplementations.find(({ name }) => name === component.structure);
    if ((await pathExists(destination)) && !force) {
        throw new Error(`The component "${componentName}" already exists, and force was not passed (--force).`);
    }
    return copyItemFromCache('systems', [system.name, structure.directory, component.name], destination, force);
}
