import path from 'node:path';
import { ExitCode, processPatternList, sair } from '../helpers/index.js';
import { chalk } from '../../core/config/index.js';
import { scanRepository } from '../../core/execution/index.js';
import { getMessages } from '../../core/messages/index.js';
import { otimizarSvgLikeSvgo } from '../../shared/formatters/index.js';
import { salvarEstado } from '../../shared/persistence/index.js';
import { Command } from 'commander';
import micromatch from 'micromatch';
const { log, CliOtimizarSvgExtraMensagens } = getMessages();
function formatBytes(bytes) {
    if (!Number.isFinite(bytes) || bytes < 0)
        return String(bytes);
    if (bytes < 1024)
        return `${bytes}B`;
    const kb = bytes / 1024;
    if (kb < 1024)
        return `${kb.toFixed(1)}KB`;
    const mb = kb / 1024;
    return `${mb.toFixed(1)}MB`;
}
export function comandoOtimizarSvg(aplicarFlagsGlobais) {
    return new Command('otimizar-svg').description(CliOtimizarSvgExtraMensagens.descricao).option('--dir <caminho>', 'Diretório base (default: CWD)').option('--write', 'Aplica otimizações no filesystem', false).option('--dry', 'Executa em modo somente leitura (default)', true).option('--include <padrao>', 'Glob pattern a INCLUIR (pode repetir ou separar por vírgula/espaço)', (val, prev) => {
        prev.push(val);
        return prev;
    }, []).option('--exclude <padrao>', 'Glob pattern a EXCLUIR adicionalmente (pode repetir ou separar por vírgula/espaço)', (val, prev) => {
        prev.push(val);
        return prev;
    }, []).action(async function (opts) {
        try {
            await aplicarFlagsGlobais(this.parent && typeof this.parent.opts === 'function' ? this.parent.opts() : {});
            const write = Boolean(opts.write);
            const dry = write ? false : Boolean(opts.dry ?? true);
            const baseDir = path.resolve(opts.dir || process.cwd());
            const includeList = processPatternList(opts.include);
            const excludeList = processPatternList(opts.exclude);
            log.info(chalk.bold(CliOtimizarSvgExtraMensagens.titulo));
            const files = await scanRepository(baseDir, {
                includeContent: true,
                filter: relPath => relPath.toLowerCase().endsWith('.svg')
            });
            const entries = Object.values(files);
            let total = 0;
            let candidates = 0;
            let optimized = 0;
            let savedBytes = 0;
            for (const erro of entries) {
                const relPath = erro.relPath;
                total++;
                if (excludeList.length && micromatch.isMatch(relPath, excludeList))
                    continue;
                if (includeList.length) {
                    const matchGlob = micromatch.isMatch(relPath, includeList);
                    const matchExact = includeList.some(caminho => String(caminho).trim() === relPath);
                    if (!matchGlob && !matchExact)
                        continue;
                }
                const src = typeof erro.content === 'string' ? erro.content : '';
                if (!src || !/<svg\b/i.test(src))
                    continue;
                const opt = otimizarSvgLikeSvgo({
                    svg: src,
                    pretty: true
                });
                if (!opt.changed)
                    continue;
                candidates++;
                const saved = opt.originalBytes - opt.optimizedBytes;
                savedBytes += saved;
                if (!dry) {
                    const abs = path.resolve(baseDir, relPath);
                    await salvarEstado(abs, opt.data);
                    optimized++;
                    log.info(CliOtimizarSvgExtraMensagens.arquivoOtimizado.replace('{arquivo}', relPath).replace('{original}', formatBytes(opt.originalBytes)).replace('{otimizado}', formatBytes(opt.optimizedBytes)).replace('{economia}', formatBytes(saved)));
                }
                else {
                    log.info(CliOtimizarSvgExtraMensagens.arquivoOtimizadoDry.replace('{arquivo}', relPath).replace('{original}', formatBytes(opt.originalBytes)).replace('{otimizado}', formatBytes(opt.optimizedBytes)).replace('{economia}', formatBytes(saved)));
                }
            }
            if (!candidates) {
                log.info(CliOtimizarSvgExtraMensagens.nenhumSvgAcimaLimiar);
                sair(ExitCode.Ok);
                return;
            }
            log.info(CliOtimizarSvgExtraMensagens.candidatosSvg.replace('{candidatos}', String(candidates)).replace('{economiaTotal}', formatBytes(savedBytes)).replace('{total}', String(total)));
            if (write) {
                log.sucesso(CliOtimizarSvgExtraMensagens.otimizacaoAplicada.replace('{aplicados}', String(optimized)).replace('{candidatos}', String(candidates)));
            }
            else {
                log.info(CliOtimizarSvgExtraMensagens.useWriteAplicar);
            }
            sair(ExitCode.Ok);
            return;
        }
        catch (err) {
            log.erro(CliOtimizarSvgExtraMensagens.falhaOtimizarSvg.replace('{erro}', err instanceof Error ? err.message : String(err)));
            sair(ExitCode.Failure);
            return;
        }
    });
}
//# sourceMappingURL=command-optimize-svg.js.map