import { normalizarFimDeLinha, normalizarNewlinesFinais, removerBom, removerEspacosFinaisPorLinha } from './commons.js';
function tentarRecuperarJson(input) {
    const changes = [];
    let code = input;
    const semComentariosLinha = code.replace(/\/\/[^\n]*/g, () => {
        changes.push('removed-line-comments');
        return '';
    });
    if (semComentariosLinha !== code) {
        code = semComentariosLinha;
    }
    const semComentariosBloco = code.replace(/\/\*[\s\S]*?\*\//g, () => {
        changes.push('removed-block-comments');
        return '';
    });
    if (semComentariosBloco !== code) {
        code = semComentariosBloco;
    }
    if (code.includes("'")) {
        let comAspasDuplas = '';
        let inString = false;
        let stringChar = '';
        let escaped = false;
        for (let indice = 0; indice < code.length; indice++) {
            const ch = code[indice];
            if (ch === undefined)
                break;
            if (escaped) {
                comAspasDuplas += ch;
                escaped = false;
                continue;
            }
            if (ch === '\\') {
                comAspasDuplas += ch;
                escaped = true;
                continue;
            }
            if (!inString) {
                if (ch === "'") {
                    inString = true;
                    stringChar = "'";
                    comAspasDuplas += '"';
                    changes.push('single-to-double-quotes');
                    continue;
                }
                comAspasDuplas += ch;
            }
            else {
                if (ch === stringChar) {
                    inString = false;
                    comAspasDuplas += '"';
                    continue;
                }
                if (ch === '"') {
                    comAspasDuplas += '\\"';
                    changes.push('escaped-internal-double-quotes');
                    continue;
                }
                comAspasDuplas += ch;
            }
        }
        code = comAspasDuplas;
    }
    const semTrailingCommas = code.replace(/,(\s*[}\]])/g, (_match, after) => {
        changes.push('removed-trailing-commas');
        return after;
    });
    if (semTrailingCommas !== code) {
        code = semTrailingCommas;
    }
    const openBraces = (code.match(/{/g) ?? []).length;
    const closeBraces = (code.match(/}/g) ?? []).length;
    const openBrackets = (code.match(/\[/g) ?? []).length;
    const closeBrackets = (code.match(/]/g) ?? []).length;
    if (openBraces > closeBraces) {
        code += '}'.repeat(openBraces - closeBraces);
        changes.push('added-closing-braces');
    }
    if (openBrackets > closeBrackets) {
        code += ']'.repeat(openBrackets - closeBrackets);
        changes.push('added-closing-brackets');
    }
    const keysSemAspas = code.replace(/(?<=[{,]\s*)([a-zA-Z_$][\w$]*)(\s*:)/g, '"$1"$2');
    if (keysSemAspas !== code) {
        code = keysSemAspas;
        changes.push('quoted-unquoted-keys');
    }
    return {
        recovered: code,
        changes
    };
}
export function formatarJsonMinimo(code) {
    try {
        const normalizedInput = normalizarFimDeLinha(removerBom(code));
        const parsed = JSON.parse(normalizedInput);
        const formatted = normalizarNewlinesFinais(JSON.stringify(parsed, null, 2));
        const normalizedForComparison = normalizarNewlinesFinais(removerEspacosFinaisPorLinha(normalizedInput));
        const changed = formatted !== normalizedForComparison;
        return {
            ok: true,
            parser: 'json',
            formatted,
            changed
        };
    }
    catch (err) {
        const { recovered, changes } = tentarRecuperarJson(normalizarFimDeLinha(removerBom(code)));
        try {
            const parsed = JSON.parse(recovered);
            const formatted = normalizarNewlinesFinais(JSON.stringify(parsed, null, 2));
            return {
                ok: true,
                parser: 'json',
                formatted,
                changed: true,
                reason: `json-recovered(${changes.join(',')})`
            };
        }
        catch {
            return {
                ok: false,
                parser: 'json',
                error: err instanceof Error ? err.message : String(err)
            };
        }
    }
}
//# sourceMappingURL=json.js.map