import { corrigirPontuacaoECodigo, normalizarFimDeLinha, normalizarNewlinesFinais, removerBom } from './commons.js';
export function formatarGitignoreMinimo(code) {
    const normalized = normalizarFimDeLinha(removerBom(code));
    const lines = normalized.split('\n');
    const sections = [];
    let currentSection = { patterns: [] };
    for (const raw of lines) {
        const trimmed = raw.trimEnd();
        if (!trimmed) {
            if (currentSection.patterns.length > 0 || currentSection.comment) {
                if (sections.length === 0 || currentSection.patterns.length > 0 || currentSection.comment) {
                    sections.push(currentSection);
                    currentSection = { patterns: [] };
                }
            }
            continue;
        }
        if (trimmed.startsWith('#')) {
            if (currentSection.patterns.length > 0) {
                sections.push(currentSection);
                currentSection = { patterns: [] };
            }
            const commentText = /^#\S/.test(trimmed) ? `# ${trimmed.slice(1).trim()}` : trimmed;
            currentSection.comment = commentText;
            continue;
        }
        const pattern = trimmed.replace(/(?<!\\)\s+/g, ' ').trim();
        if (pattern) {
            currentSection.patterns.push(pattern);
        }
    }
    if (currentSection.patterns.length > 0 || currentSection.comment) {
        sections.push(currentSection);
    }
    const out = [];
    let firstSection = true;
    for (const section of sections) {
        if (!firstSection && (section.comment || section.patterns.length > 0)) {
            out.push('');
        }
        firstSection = false;
        if (section.comment) {
            out.push(section.comment);
        }
        const sortedPatterns = [...section.patterns].sort((a, b) => {
            const aNegated = a.startsWith('!');
            const bNegated = b.startsWith('!');
            if (aNegated !== bNegated)
                return aNegated ? 1 : -1;
            return a.localeCompare(b);
        });
        for (const pattern of sortedPatterns) {
            out.push(pattern);
        }
    }
    const { text: comPontuacao, stats } = corrigirPontuacaoECodigo(out.join('\n'));
    const formatted = normalizarNewlinesFinais(comPontuacao);
    const baseline = normalizarNewlinesFinais(normalized);
    const anyChanged = formatted !== baseline;
    return {
        ok: true,
        parser: 'gitignore',
        formatted,
        changed: anyChanged,
        reason: anyChanged ? `estilo-tutanus-gitignore(punct:${stats.pontuacaoRepetida},space:${stats.espacamentoIncorreto},ops:${stats.operadoresRelacionais})` : 'normalizacao-basica'
    };
}
export function formatarEditorconfigMinimo(code) {
    const normalized = normalizarFimDeLinha(removerBom(code));
    const lines = normalized.split('\n');
    const out = [];
    let currentSection = '';
    let currentEntries = [];
    const flushSection = () => {
        if (currentSection) {
            out.push(`[${currentSection}]`);
            if (currentEntries.length > 0) {
                const maxKeyLen = Math.max(...currentEntries.map(erro => erro.key.length));
                for (const entry of currentEntries) {
                    const paddedKey = entry.key.padEnd(maxKeyLen);
                    const commentPart = entry.comment ? ` ${entry.comment}` : '';
                    out.push(`${paddedKey} = ${entry.value}${commentPart}`);
                }
            }
            out.push('');
            currentEntries = [];
            currentSection = '';
        }
    };
    for (const raw of lines) {
        const trimmed = raw.trim();
        if (!trimmed) {
            continue;
        }
        if (trimmed.startsWith('#') || trimmed.startsWith(';')) {
            if (currentSection && currentEntries.length > 0) {
                currentEntries[currentEntries.length - 1].comment = trimmed;
            }
            else {
                out.push(trimmed);
            }
            continue;
        }
        const sectionMatch = trimmed.match(/^\[(.+)\]$/);
        if (sectionMatch) {
            flushSection();
            currentSection = sectionMatch[1]?.trim() ?? '';
            continue;
        }
        const eqIdx = trimmed.indexOf('=');
        if (eqIdx > 0 && currentSection) {
            const key = trimmed.slice(0, eqIdx).trim().toLowerCase();
            const val = trimmed.slice(eqIdx + 1).trim();
            currentEntries.push({
                key,
                value: val
            });
            continue;
        }
        out.push(trimmed);
    }
    flushSection();
    const { text: comPontuacao, stats } = corrigirPontuacaoECodigo(out.join('\n').replace(/\n{3,}/g, '\n\n'));
    const formatted = normalizarNewlinesFinais(comPontuacao);
    const baseline = normalizarNewlinesFinais(normalized);
    const anyChanged = formatted !== baseline;
    return {
        ok: true,
        parser: 'editorconfig',
        formatted,
        changed: anyChanged,
        reason: anyChanged ? `estilo-tutanus-editorconfig(punct:${stats.pontuacaoRepetida},space:${stats.espacamentoIncorreto},ops:${stats.operadoresRelacionais})` : 'normalizacao-basica'
    };
}
export function formatarNpmrcMinimo(code) {
    const normalized = normalizarFimDeLinha(removerBom(code));
    const lines = normalized.split('\n');
    const out = [];
    for (const raw of lines) {
        const trimmed = raw.trimEnd();
        if (!trimmed) {
            if (out.length > 0 && out[out.length - 1] !== '') {
                out.push('');
            }
            continue;
        }
        if (trimmed.startsWith('#') || trimmed.startsWith(';')) {
            if (/^[#;]\S/.test(trimmed)) {
                out.push(`${trimmed[0]} ${trimmed.slice(1).trim()}`);
            }
            else {
                out.push(trimmed);
            }
            continue;
        }
        const eqIdx = trimmed.indexOf('=');
        if (eqIdx > 0) {
            const key = trimmed.slice(0, eqIdx).trim();
            const val = trimmed.slice(eqIdx + 1).trim();
            out.push(`${key} = ${val}`);
            continue;
        }
        out.push(trimmed);
    }
    const { text: comPontuacao, stats } = corrigirPontuacaoECodigo(out.join('\n'));
    const formatted = normalizarNewlinesFinais(comPontuacao);
    const baseline = normalizarNewlinesFinais(normalized);
    const anyChanged = formatted !== baseline;
    return {
        ok: true,
        parser: 'npmrc',
        formatted,
        changed: anyChanged,
        reason: anyChanged ? `estilo-tutanus-npmrc(punct:${stats.pontuacaoRepetida},space:${stats.espacamentoIncorreto},ops:${stats.operadoresRelacionais})` : 'normalizacao-basica'
    };
}
export function formatarNvmrcMinimo(code) {
    const normalized = normalizarFimDeLinha(removerBom(code)).trim();
    const { text: comPontuacao, stats } = corrigirPontuacaoECodigo(normalized);
    const formatted = normalizarNewlinesFinais(`${comPontuacao}\n`);
    const baseline = normalizarNewlinesFinais(`${code.trim()}\n`);
    const anyChanged = formatted !== baseline;
    return {
        ok: true,
        parser: 'nvmrc',
        formatted,
        changed: anyChanged,
        reason: anyChanged ? `estilo-tutanus-nvmrc(punct:${stats.pontuacaoRepetida},space:${stats.espacamentoIncorreto},ops:${stats.operadoresRelacionais})` : 'normalizacao-basica'
    };
}
//# sourceMappingURL=dotfiles.js.map