import { CABECALHOS, messages } from '../../core/messages/index.js';
import { ativarModoJson } from '../../shared/helpers/index.js';
import { Command } from 'commander';
import ora from 'ora';
import { optionsDiagnosticar } from '../diagnostic/options-diagnose.js';
import { processarDiagnostico } from '../diagnostic/processing-diagnostic.js';
const log = messages.log;
function obterOptsParent(command) {
    const parent = command.parent;
    return parent && typeof parent.opts === 'function' ? parent.opts() : {};
}
async function aplicarFlagsCombinadas(command, opts, aplicarFlagsGlobais) {
    try {
        const parentFlags = obterOptsParent(command);
        const localFlags = typeof command.opts === 'function' ? command.opts() : {};
        const merged = {
            ...parentFlags,
            ...localFlags,
            ...opts
        };
        await aplicarFlagsGlobais(merged);
    }
    catch {
        try {
            await aplicarFlagsGlobais(opts);
        }
        catch {
        }
    }
}
async function mostrarSugestoesVerbose(opts, command, logNivel) {
    const json = Boolean(opts['json']);
    const full = Boolean(opts['full']);
    const detalhado = Boolean(opts['detalhado']);
    if (json || !(full || logNivel === 'debug' || detalhado))
        return;
    try {
        const { chalk, config } = await import('../../core/config/index.js');
        const activeFlags = [];
        const details = [];
        const parentOpts = obterOptsParent(command);
        if (json) {
            activeFlags.push('--json');
            details.push(messages.CliComandoDiagnosticarMensagens.detalheSaidaEstruturada);
        }
        if (Boolean(opts['guardianCheck'])) {
            activeFlags.push('--guardian-check');
            details.push(messages.CliComandoDiagnosticarMensagens.detalheGuardian);
        }
        if (Boolean(opts['executive'])) {
            activeFlags.push('--executive');
            details.push(messages.CliComandoDiagnosticarMensagens.detalheExecutive);
        }
        if (full) {
            activeFlags.push('--full');
            details.push(messages.CliComandoDiagnosticarMensagens.detalheFull);
        }
        if (Boolean(opts['fast'])) {
            activeFlags.push('--fast');
            details.push(messages.CliComandoDiagnosticarMensagens.detalheFast);
        }
        const localCompact = Boolean(opts['compact']);
        const effectiveCompact = localCompact || !full && !localCompact;
        if (effectiveCompact && !full) {
            activeFlags.push('--compact');
            details.push(messages.CliComandoDiagnosticarMensagens.detalheCompact);
        }
        if (Boolean(opts['listarAnalistas'])) {
            activeFlags.push('--listar-analistas');
        }
        if (Boolean(opts['autoFix'])) {
            activeFlags.push('--auto-fix');
            details.push(messages.CliComandoDiagnosticarMensagens.detalheAutoFix);
        }
        if (Boolean(opts['autoFixConservative'])) {
            activeFlags.push('--auto-fix-conservative');
            details.push(messages.CliComandoDiagnosticarMensagens.detalheAutoFixConservative);
        }
        const includes = opts['include'] || [];
        const excludes = opts['exclude'] || [];
        if (includes.length)
            details.push(messages.CliComandoDiagnosticarMensagens.detalheIncludePatterns(includes.length, includes.join(', ')));
        if (excludes.length)
            details.push(messages.CliComandoDiagnosticarMensagens.detalheExcludePatterns(excludes.length, excludes.join(', ')));
        const parentExport = Boolean(parentOpts && Object.prototype.hasOwnProperty.call(parentOpts, 'export') && Boolean(parentOpts['export']));
        const parentExportFull = Boolean(parentOpts && Object.prototype.hasOwnProperty.call(parentOpts, 'exportFull') && Boolean(parentOpts['exportFull']));
        const localExport = Boolean(opts['export']);
        const localExportFull = Boolean(opts['exportFull']);
        if (parentExport || localExport) {
            activeFlags.push('--export');
            const relDir = config && config['REPORTS_DIR'] || 'reports';
            details.push(messages.CliComandoDiagnosticarMensagens.detalheExport(String(relDir)));
        }
        if (parentExportFull || localExportFull) {
            activeFlags.push('--export-full');
            details.push(messages.CliComandoDiagnosticarMensagens.detalheExportFull);
        }
        const resolvedParentLogNivel = parentOpts && Object.prototype.hasOwnProperty.call(parentOpts, 'logLevel') ? String(parentOpts['logLevel']) : undefined;
        const effectiveLogNivel = logNivel || resolvedParentLogNivel || 'info';
        details.push(messages.CliComandoDiagnosticarMensagens.detalheLogLevel(String(effectiveLogNivel)));
        details.push(messages.CliComandoDiagnosticarMensagens.dicaPrefiraLogLevelDebug);
        details.push(messages.CliComandoDiagnosticarMensagens.dicaAutoFixConservative);
        if (activeFlags.length || details.length) {
            const header = chalk.cyan(messages.CliComandoDiagnosticarMensagens.sugestoesHeader);
            const footer = chalk.cyan(messages.CliComandoDiagnosticarMensagens.sugestoesFooter);
            log.info(header);
            if (activeFlags.length)
                log.info(chalk.yellow(`${CABECALHOS.diagnostico.flagsAtivas} `) + activeFlags.join(' '));
            else
                log.info(chalk.gray(messages.CliComandoDiagnosticarMensagens.nenhumaFlagRelevante));
            log.info(messages.CliComandoDiagnosticarMensagens.linhaEmBranco);
            log.info(chalk.green(CABECALHOS.diagnostico.informacoesUteis));
            for (const diretorio of details)
                log.info(messages.CliComandoDiagnosticarMensagens.detalheLinha(String(diretorio)));
            log.info(footer);
        }
    }
    catch {
    }
}
function criarSpinner(opts) {
    if (opts.json) {
        const stub = { text: '', start: () => stub, succeed: () => { }, fail: () => { } };
        return stub;
    }
    const spinner = ora({
        text: messages.CliComandoDiagnosticarMensagens.spinnerExecutando,
        spinner: 'dots'
    }).start();
    const logWithFase = log;
    logWithFase.fase = (textoTitulo) => {
        if (typeof textoTitulo === 'string' && textoTitulo.trim()) {
            spinner.text = messages.CliComandoDiagnosticarMensagens.spinnerFase(textoTitulo);
        }
    };
    return spinner;
}
export function comandoDiagnosticar(aplicarFlagsGlobais) {
    const cmd = new Command('diagnosticar').alias('diag').description(messages.CliComandoDiagnosticarMensagens.descricao);
    cmd.allowUnknownOption(true);
    cmd.allowExcessArguments(true);
    for (const opt of optionsDiagnosticar) {
        if ('parser' in opt && opt.parser) {
            cmd.option(opt.flags, opt.desc, opt.parser, opt.defaultValue);
        }
        else if ('defaultValue' in opt) {
            cmd.option(opt.flags, opt.desc, opt.defaultValue);
        }
        else {
            cmd.option(opt.flags, opt.desc);
        }
    }
    cmd.action(async (opts, command) => {
        await aplicarFlagsCombinadas(command, opts, aplicarFlagsGlobais);
        if (process.env.TUTANUS_TEST_FAST === '1') {
            if (opts.json) {
                console.log(JSON.stringify({
                    meta: {
                        fast: true,
                        tipo: messages.CliComandoDiagnosticarMensagens.fastModeTipo
                    },
                    totalArquivos: 0,
                    ocorrencias: []
                }, null, 2));
                return;
            }
            return;
        }
        if (opts.json) {
            ativarModoJson();
        }
        const logNivel = String(opts.logNivel || 'info');
        await mostrarSugestoesVerbose(opts, command, logNivel);
        const spinner = criarSpinner(opts);
        try {
            await processarDiagnostico(opts);
            spinner.succeed(messages.CliComandoDiagnosticarMensagens.spinnerConcluido);
        }
        catch (err) {
            spinner.fail(messages.CliComandoDiagnosticarMensagens.spinnerFalhou);
            throw err;
        }
    });
    return cmd;
}
//# sourceMappingURL=command-diagnose.js.map