import { join } from 'node:path';
import { buildCommandContext, } from '../../app/command-context.js';
import { readGlobalOptions } from '../shared/shared.utils.js';
import { resolveEffectiveConfig } from '../../config/resolve.js';
import { resolveProjectRoot } from '../../fs/paths.js';
import { Command } from 'commander';
const DEFAULT_DEPENDENCIES = {
    buildCommandContext,
    resolveProjectRoot,
    resolveEffectiveConfig,
    processEnv: process.env,
};
function formatConfigDump(result) {
    const lines = [];
    const grouped = new Map();
    for (const [key, entry] of Object.entries(result.resolved).sort(([a], [b]) => a.localeCompare(b))) {
        const items = grouped.get(entry.source) ?? [];
        items.push(`${key} = ${String(entry.value)}`);
        grouped.set(entry.source, items);
    }
    for (const source of ['shared', 'local', 'user', 'env', 'default']) {
        const items = grouped.get(source);
        if (!items || items.length === 0) {
            continue;
        }
        if (lines.length > 0) {
            lines.push('');
        }
        lines.push(`${source}:`);
        for (const item of items) {
            lines.push(`  ${item}`);
        }
    }
    return lines;
}
async function runConfigDump(context, dependencies) {
    try {
        const repoRoot = await dependencies.resolveProjectRoot(context.cwd);
        const userConfigDir = join(context.home, '.oat');
        const result = await dependencies.resolveEffectiveConfig(repoRoot, userConfigDir, dependencies.processEnv);
        if (context.json) {
            context.logger.json({
                status: 'ok',
                ...result,
            });
        }
        else {
            for (const line of formatConfigDump(result)) {
                context.logger.info(line);
            }
        }
        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 createConfigDumpCommand(overrides = {}) {
    const dependencies = {
        ...DEFAULT_DEPENDENCIES,
        ...overrides,
    };
    return new Command('dump')
        .description('Dump merged OAT config with source attribution')
        .action(async (_options, command) => {
        const context = dependencies.buildCommandContext(readGlobalOptions(command));
        await runConfigDump(context, dependencies);
    });
}
