import { execFile } from 'node:child_process';
import { buildCommandContext } from '../../../app/command-context.js';
import { consumeInitToolsRunMetadata, createInitToolsCommand, } from '../../init/tools/index.js';
import { withScopeOption } from '../../shared/scope-option.js';
import { readGlobalOptions, resolveConcreteScopes, } from '../../shared/shared.utils.js';
import { autoSync, } from '../../tools/shared/auto-sync.js';
import { getInstalledCanonicalPaths as getInstallSyncCanonicalPaths } from '../../tools/shared/install-sync-context.js';
const defaultSyncDependencies = {
    runSync: async ({ scope, cwd, installedCanonicalPaths }) => {
        const syncArgs = [
            ...process.execArgv,
            process.argv[1],
            'sync',
            '--scope',
            scope,
        ];
        for (const canonicalPath of installedCanonicalPaths ?? []) {
            syncArgs.push('--install-canonical', canonicalPath);
        }
        await new Promise((resolve, reject) => {
            execFile(process.execPath, syncArgs, { cwd }, (error) => {
                if (error)
                    reject(error);
                else
                    resolve();
            });
        });
    },
};
export function createToolsInstallCommand(syncDependencies = defaultSyncDependencies, initOverrides = {}, createBaseCommand) {
    const cmd = createBaseCommand === undefined
        ? createInitToolsCommand(initOverrides)
        : createBaseCommand();
    cmd.name('install');
    withScopeOption(cmd);
    cmd.option('--no-sync', 'Skip auto-sync after install');
    cmd.hook('postAction', async (thisCommand, actionCommand) => {
        if (process.exitCode !== 0 && process.exitCode !== undefined)
            return;
        const opts = thisCommand.opts();
        if (opts.sync === false)
            return;
        const globalOptions = readGlobalOptions(actionCommand);
        const buildContext = initOverrides.buildCommandContext ?? buildCommandContext;
        const context = buildContext(globalOptions);
        const metadata = consumeInitToolsRunMetadata();
        const scopes = metadata === null
            ? resolveConcreteScopes(context.scope)
            : metadata.affectedScopes;
        const installedCanonicalPaths = getInstallSyncCanonicalPaths(actionCommand);
        await autoSync(scopes, context.cwd, context.home, context.logger, syncDependencies, { installedCanonicalPaths });
    });
    return cmd;
}
