import { buildCommandContext, } from '../../../../app/command-context.js';
import { withScopeOption } from '../../../shared/scope-option.js';
import { confirmAction, selectManyWithAbort, } from '../../../shared/shared.prompts.js';
import { readGlobalOptions } from '../../../shared/shared.utils.js';
import { canonicalSkillPaths, setInstalledCanonicalPaths, } from '../../../tools/shared/install-sync-context.js';
import { resolveAssetsRoot } from '../../../../fs/assets.js';
import { resolveProjectRoot, resolveScopeRoot } from '../../../../fs/paths.js';
import { Command } from 'commander';
import { installUtility as defaultInstallUtility, UTILITY_SKILLS, } from './install-utility.js';
const DEFAULT_DEPENDENCIES = {
    buildCommandContext,
    resolveProjectRoot,
    resolveScopeRoot,
    resolveAssetsRoot,
    installUtility: defaultInstallUtility,
    selectManyWithAbort,
    confirmAction,
};
function resolveScope(context) {
    return context.scope === 'user' ? 'user' : 'project';
}
function reportSuccess(context, scope, targetRoot, assetsRoot, selectedSkills, result) {
    if (context.json) {
        context.logger.json({
            status: 'ok',
            scope,
            targetRoot,
            assetsRoot,
            selectedSkills,
            result,
        });
        return;
    }
    context.logger.info('Installed utility tool pack.');
    context.logger.info(`Scope: ${scope}`);
    context.logger.info(`Target root: ${targetRoot}`);
    context.logger.info(`Selected skills: ${selectedSkills.join(', ') || '(none)'}`);
    context.logger.info(`Skills: copied=${result.copiedSkills.length}, updated=${result.updatedSkills.length}, skipped=${result.skippedSkills.length}`);
    context.logger.info(`Run: oat sync --scope ${scope}`);
}
async function runInitToolsUtility(context, options, dependencies, command) {
    try {
        const scope = resolveScope(context);
        const targetRoot = scope === 'project'
            ? await dependencies.resolveProjectRoot(context.cwd)
            : dependencies.resolveScopeRoot('user', context.cwd, context.home);
        const selectedSkills = context.interactive
            ? await dependencies.selectManyWithAbort('Select utility skills to install', UTILITY_SKILLS.map((skill) => ({
                label: skill,
                value: skill,
                checked: true,
            })), { interactive: context.interactive })
            : [...UTILITY_SKILLS];
        if (selectedSkills === null) {
            if (!context.json) {
                context.logger.info('Cancelled: no utility skills installed.');
            }
            process.exitCode = 0;
            return;
        }
        if (selectedSkills.length === 0) {
            if (!context.json) {
                context.logger.info('No utility skills selected.');
            }
            process.exitCode = 0;
            return;
        }
        if (options.force && context.interactive) {
            const confirmed = await dependencies.confirmAction(`Force overwrite existing utility assets in ${scope} scope?`, { interactive: context.interactive });
            if (!confirmed) {
                if (!context.json) {
                    context.logger.info('Cancelled: no files were overwritten.');
                }
                process.exitCode = 0;
                return;
            }
        }
        const assetsRoot = await dependencies.resolveAssetsRoot();
        const result = await dependencies.installUtility({
            assetsRoot,
            targetRoot,
            skills: selectedSkills,
            force: options.force,
        });
        setInstalledCanonicalPaths(command, canonicalSkillPaths(selectedSkills));
        reportSuccess(context, scope, targetRoot, assetsRoot, selectedSkills, result);
        process.exitCode = 0;
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        if (context.json) {
            context.logger.json({ status: 'error', message });
        }
        else {
            context.logger.error(message);
        }
        process.exitCode = 1;
    }
}
export function createInitToolsUtilityCommand(overrides = {}) {
    const dependencies = {
        ...DEFAULT_DEPENDENCIES,
        ...overrides,
    };
    return withScopeOption(new Command('utility'))
        .description('Install OAT utility skills')
        .option('--force', 'Overwrite existing files where applicable')
        .action(async (options, command) => {
        const context = dependencies.buildCommandContext(readGlobalOptions(command));
        await runInitToolsUtility(context, options, dependencies, command);
    });
}
