import { corrigirPontuacaoECodigo, normalizarFimDeLinha, normalizarNewlinesFinais, removerBom } from './commons.js';
function parseTomlLines(code) {
    const lines = normalizarFimDeLinha(code).split('\n');
    const result = [];
    let inMultilineString = false;
    let inArrayValue = false;
    for (const raw of lines) {
        const trimmed = raw.trim();
        const indent = raw.length - trimmed.length;
        if (inMultilineString) {
            if (trimmed.includes('"""') || trimmed.includes("'''")) {
                inMultilineString = false;
            }
            result.push({
                raw,
                kind: 'multiline-string-content',
                indent
            });
            continue;
        }
        if (inArrayValue) {
            if (trimmed.includes(']')) {
                inArrayValue = false;
            }
            result.push({
                raw,
                kind: 'array-value-continuation',
                indent
            });
            continue;
        }
        if (!trimmed) {
            result.push({
                raw,
                kind: 'empty',
                indent
            });
            continue;
        }
        if (trimmed.startsWith('#')) {
            result.push({
                raw,
                kind: 'comment',
                indent
            });
            continue;
        }
        if (/^\[\[.+\]\]$/.test(trimmed)) {
            result.push({
                raw,
                kind: 'array-of-tables',
                indent
            });
            continue;
        }
        if (/^\[.+\]$/.test(trimmed)) {
            result.push({
                raw,
                kind: 'section',
                indent
            });
            continue;
        }
        if (/=\s*"""/.test(trimmed) || /=\s*'''/.test(trimmed)) {
            if (!trimmed.endsWith('"""') && !trimmed.endsWith("'''")) {
                inMultilineString = true;
            }
            result.push({
                raw,
                kind: 'multiline-string',
                indent
            });
            continue;
        }
        if (/=\s*\[/.test(trimmed) && !trimmed.includes(']')) {
            inArrayValue = true;
            result.push({
                raw,
                kind: 'array-value-start',
                indent
            });
            continue;
        }
        if (/=\s*\{/.test(trimmed)) {
            result.push({
                raw,
                kind: 'inline-table',
                indent
            });
            continue;
        }
        result.push({
            raw,
            kind: 'key-value',
            indent
        });
    }
    return result;
}
function corrigirEspacamentoToml(entries) {
    const out = [];
    for (const entry of entries) {
        if (entry.kind === 'empty' || entry.kind === 'comment' || entry.kind === 'multiline-string-content' || entry.kind === 'array-value-continuation') {
            out.push(entry);
            continue;
        }
        let fixed = entry.raw;
        if (entry.kind === 'key-value' || entry.kind === 'multiline-string') {
            const eqIdx = fixed.indexOf('=');
            if (eqIdx > 0) {
                const before = fixed.slice(0, eqIdx);
                const after = fixed.slice(eqIdx + 1);
                if (!before.endsWith(' ') && !after.startsWith(' ')) {
                    fixed = `${before.trimEnd()} = ${after.trimStart()}`;
                }
                else if (!before.endsWith(' ')) {
                    fixed = `${before.trimEnd()} =${after}`;
                }
                else if (!after.startsWith(' ')) {
                    fixed = `${before}=${after.trimStart()}`;
                }
            }
        }
        if (entry.kind === 'section') {
            const inner = fixed.replace(/^\[/, '').replace(/\]$/, '').trim();
            fixed = `[${inner}]`;
        }
        if (entry.kind === 'array-of-tables') {
            const inner = fixed.replace(/^\[\[/, '').replace(/\]\]$/, '').trim();
            fixed = `[[${inner}]]`;
        }
        if (fixed !== entry.raw) {
            out.push({
                ...entry,
                raw: fixed
            });
        }
        else {
            out.push(entry);
        }
    }
    return out;
}
export function formatarTomlMinimo(code) {
    const normalized = normalizarFimDeLinha(removerBom(code));
    const entries = parseTomlLines(normalized);
    const corrigidos = corrigirEspacamentoToml(entries);
    const rebuilt = corrigidos.map(erro => erro.raw).join('\n');
    const lines = rebuilt.split('\n');
    const out = [];
    let currentSection = [];
    const flushSection = () => {
        if (currentSection.length > 0) {
            const realEntries = currentSection.filter(erro => !erro.comment);
            const maxKeyLen = realEntries.length > 0 ? Math.max(...realEntries.map(erro => erro.key.length)) : 0;
            for (const entry of currentSection) {
                if (entry.comment) {
                    out.push(entry.comment);
                }
                else {
                    const paddedKey = entry.key.padEnd(maxKeyLen);
                    out.push(`${paddedKey} = ${entry.value}`);
                }
            }
            currentSection = [];
        }
    };
    for (const line of lines) {
        const trimmed = line.trim();
        if (!trimmed) {
            flushSection();
            if (out.length > 0 && out[out.length - 1] !== '') {
                out.push('');
            }
            continue;
        }
        if (trimmed.startsWith('#')) {
            if (currentSection.length > 0 && currentSection[currentSection.length - 1] && !currentSection[currentSection.length - 1].comment) {
                currentSection.push({
                    key: '',
                    value: '',
                    comment: trimmed,
                    raw: line
                });
            }
            else {
                flushSection();
                out.push(trimmed);
            }
            continue;
        }
        if (/^\[/.test(trimmed)) {
            flushSection();
            if (out.length > 0 && out[out.length - 1] !== '') {
                out.push('');
            }
            const isArrayOfTables = /^\[\[/.test(trimmed);
            if (isArrayOfTables) {
                const inner = trimmed.replace(/^\[\[/, '').replace(/\]\]$/, '').trim();
                out.push(`[[${inner}]]`);
            }
            else {
                const inner = trimmed.replace(/^\[/, '').replace(/\]$/, '').trim();
                out.push(`[${inner}]`);
            }
            continue;
        }
        const eqIdx = trimmed.indexOf('=');
        if (eqIdx > 0) {
            const key = trimmed.slice(0, eqIdx).trim();
            const val = trimmed.slice(eqIdx + 1).trim();
            currentSection.push({
                key,
                value: val,
                comment: '',
                raw: line
            });
            continue;
        }
        out.push(trimmed);
    }
    flushSection();
    const { text: comPontuacao, stats } = corrigirPontuacaoECodigo(out.join('\n'));
    const formatted = normalizarNewlinesFinais(comPontuacao);
    const baseline = normalizarNewlinesFinais(normalized);
    const anyChanged = formatted !== baseline;
    return {
        ok: true,
        parser: 'toml',
        formatted,
        changed: anyChanged,
        reason: anyChanged ? `estilo-tutanus-toml(punct:${stats.pontuacaoRepetida},space:${stats.espacamentoIncorreto},ops:${stats.operadoresRelacionais})` : 'normalizacao-basica'
    };
}
export function formatarIniMinimo(code) {
    const normalized = normalizarFimDeLinha(removerBom(code));
    const lines = normalized.split('\n');
    const out = [];
    let currentSection = [];
    const flushSection = () => {
        if (currentSection.length > 0) {
            const realEntries = currentSection.filter(erro => !erro.comment);
            const maxKeyLen = realEntries.length > 0 ? Math.max(...realEntries.map(erro => erro.key.length)) : 0;
            for (const entry of currentSection) {
                if (entry.comment) {
                    out.push(entry.comment);
                }
                else {
                    const paddedKey = entry.key.padEnd(maxKeyLen);
                    out.push(`${paddedKey} = ${entry.value}`);
                }
            }
            currentSection = [];
        }
    };
    for (const line of lines) {
        const trimmed = line.trim();
        if (!trimmed) {
            flushSection();
            if (out.length > 0 && out[out.length - 1] !== '') {
                out.push('');
            }
            continue;
        }
        if (trimmed.startsWith('#') || trimmed.startsWith(';')) {
            if (currentSection.length > 0 && currentSection[currentSection.length - 1] && !currentSection[currentSection.length - 1].comment) {
                currentSection.push({
                    key: '',
                    value: '',
                    comment: trimmed
                });
            }
            else {
                flushSection();
                out.push(trimmed);
            }
            continue;
        }
        if (/^\[/.test(trimmed) && /\]$/.test(trimmed)) {
            flushSection();
            if (out.length > 0 && out[out.length - 1] !== '') {
                out.push('');
            }
            const inner = trimmed.slice(1, -1).trim();
            out.push(`[${inner}]`);
            continue;
        }
        const eqIdx = trimmed.indexOf('=');
        if (eqIdx > 0) {
            const key = trimmed.slice(0, eqIdx).trim();
            const val = trimmed.slice(eqIdx + 1).trim();
            currentSection.push({
                key,
                value: val,
                comment: ''
            });
            continue;
        }
        out.push(trimmed);
    }
    flushSection();
    const { text: comPontuacao, stats } = corrigirPontuacaoECodigo(out.join('\n'));
    const formatted = normalizarNewlinesFinais(comPontuacao);
    const baseline = normalizarNewlinesFinais(normalized);
    const anyChanged = formatted !== baseline;
    return {
        ok: true,
        parser: 'ini',
        formatted,
        changed: anyChanged,
        reason: anyChanged ? `estilo-tutanus-ini(punct:${stats.pontuacaoRepetida},space:${stats.espacamentoIncorreto},ops:${stats.operadoresRelacionais})` : 'normalizacao-basica'
    };
}
//# sourceMappingURL=toml.js.map