import { corrigirPontuacaoECodigo, limitarLinhasEmBranco, normalizarFimDeLinha, normalizarNewlinesFinais, removerBom } from './commons.js';
function parsePropertiesLines(code) {
    const lines = normalizarFimDeLinha(code).split('\n');
    const result = [];
    let inContinuation = false;
    for (const raw of lines) {
        const trimmed = raw.trim();
        if (inContinuation) {
            const isLast = !trimmed.endsWith('\\');
            if (isLast) {
                inContinuation = false;
            }
            result.push({
                raw,
                kind: 'continuation',
                key: '',
                value: trimmed
            });
            continue;
        }
        if (!trimmed) {
            result.push({
                raw,
                kind: 'empty',
                key: '',
                value: ''
            });
            continue;
        }
        if (trimmed.startsWith('#') || trimmed.startsWith('!')) {
            result.push({
                raw,
                kind: 'comment',
                key: '',
                value: trimmed
            });
            continue;
        }
        const sepMatch = trimmed.match(/^([^:=]+?)\s*[:=]\s*(.*)$/);
        if (sepMatch) {
            const key = (sepMatch[1] ?? '').trim();
            const val = (sepMatch[2] ?? '').trim();
            const isContinuation = val.endsWith('\\');
            if (isContinuation) {
                inContinuation = true;
            }
            result.push({
                raw,
                kind: 'key-value',
                key,
                value: val
            });
            continue;
        }
        result.push({
            raw,
            kind: 'native',
            key: '',
            value: trimmed
        });
    }
    return result;
}
function corrigirEspacamentoProperties(entries) {
    const out = [];
    for (const entry of entries) {
        if (entry.kind === 'empty' || entry.kind === 'comment' || entry.kind === 'continuation' || entry.kind === 'native') {
            out.push(entry);
            continue;
        }
        const fixed = `${entry.key} = ${entry.value}`;
        if (fixed !== entry.raw) {
            out.push({
                ...entry,
                raw: fixed
            });
        }
        else {
            out.push(entry);
        }
    }
    return out;
}
function corrigirUnicodeEscapes(entries) {
    const out = [];
    for (const entry of entries) {
        if (entry.kind !== 'key-value') {
            out.push(entry);
            continue;
        }
        const decoded = entry.value.replace(/\\u([0-9a-fA-F]{4})/g, (_match, hex) => {
            return String.fromCharCode(parseInt(hex, 16));
        });
        if (decoded !== entry.value) {
            out.push({
                ...entry,
                value: decoded,
                raw: `${entry.key} = ${decoded}`
            });
        }
        else {
            out.push(entry);
        }
    }
    return out;
}
export function formatarPropertiesMinimo(code) {
    const normalized = normalizarFimDeLinha(removerBom(code));
    const entries = parsePropertiesLines(normalized);
    const comEspacamento = corrigirEspacamentoProperties(entries);
    const comUnicode = corrigirUnicodeEscapes(comEspacamento);
    const rebuilt = comUnicode.map(erro => erro.raw).join('\n');
    const { code: limitado } = limitarLinhasEmBranco(rebuilt, 2);
    const { text: comPontuacao, stats } = corrigirPontuacaoECodigo(limitado);
    const formatted = normalizarNewlinesFinais(comPontuacao);
    const baseline = normalizarNewlinesFinais(normalized);
    const anyChanged = formatted !== baseline;
    return {
        ok: true,
        parser: 'properties',
        formatted,
        changed: anyChanged,
        reason: anyChanged ? `estilo-tutanus-properties(punct:${stats.pontuacaoRepetida},space:${stats.espacamentoIncorreto},ops:${stats.operadoresRelacionais})` : 'normalizacao-basica'
    };
}
export function formatarGradleMinimo(code) {
    const normalized = normalizarFimDeLinha(removerBom(code));
    const lines = normalized.split('\n');
    const out = [];
    let inMultilineComment = false;
    let prevWasBlock = false;
    for (const raw of lines) {
        const trimmed = raw.trim();
        if (inMultilineComment) {
            out.push(raw);
            if (trimmed.includes('*/')) {
                inMultilineComment = false;
            }
            continue;
        }
        if (trimmed.startsWith('/*') && !trimmed.includes('*/')) {
            inMultilineComment = true;
            out.push(raw);
            continue;
        }
        if (trimmed.startsWith('//')) {
            out.push(raw);
            continue;
        }
        if (!trimmed) {
            out.push(raw);
            continue;
        }
        if (/^(dependencies|plugins|repositories|buildscript|subprojects|allprojects|configurations)\s*[\{]/.test(trimmed)) {
            if (prevWasBlock === false && out.length > 0 && out[out.length - 1] !== '') {
                out.push('');
            }
            prevWasBlock = true;
        }
        else {
            prevWasBlock = false;
        }
        out.push(raw.replace(/[ \t]+$/, ''));
    }
    const { code: limitado } = limitarLinhasEmBranco(out.join('\n'), 2);
    const { text: comPontuacao, stats } = corrigirPontuacaoECodigo(limitado);
    const formatted = normalizarNewlinesFinais(comPontuacao);
    const baseline = normalizarNewlinesFinais(normalized);
    const anyChanged = formatted !== baseline;
    return {
        ok: true,
        parser: 'gradle',
        formatted,
        changed: anyChanged,
        reason: anyChanged ? `estilo-tutanus-gradle(punct:${stats.pontuacaoRepetida},space:${stats.espacamentoIncorreto},ops:${stats.operadoresRelacionais})` : 'normalizacao-basica'
    };
}
//# sourceMappingURL=properties.js.map