import { messages } from '../../../core/messages/index.js';
import { createLineLookup, maskGoComments } from '../../../shared/helpers/index.js';
import { criarAnalista, criarOcorrencia } from '../../../types/index.js';
const disableEnv = process.env.TUTANUS_DISABLE_PLUGIN_GO === '1';
function warn(message, relPath, line, nivel) {
    return criarOcorrencia({
        relPath,
        mensagem: message,
        linha: line,
        nivel: nivel ?? messages.SeverityNiveis.warning,
        origem: messages.AnalystOrigens.go,
        tipo: messages.AnalystTipos.go
    });
}
function collectBestPractices(src, relPath) {
    const ocorrencias = [];
    const lineOf = createLineLookup(src).lineAt;
    const scan = maskGoComments(src);
    for (const match of scan.matchAll(/(?:if|case|return|switch|default|for|&&|\|\|)\s+.*[=!]=\s*(\d{4,})\b/g)) {
        const line = lineOf(match.index);
        ocorrencias.push(warn(messages.GoMensagens.magicNumber, relPath, line, messages.SeverityNiveis.suggestion));
    }
    const funcMatches = src.matchAll(/(?:^|\n)\s*func\s+\w+.*?\{/gs);
    for (const funcMatch of funcMatches) {
        const startIdx = (funcMatch.index ?? 0) + (funcMatch[0]?.length ?? 0);
        let braceCount = 1;
        let endIdx = startIdx;
        for (let i = startIdx; i < src.length && braceCount > 0; i++) {
            if (src[i] === '{')
                braceCount++;
            if (src[i] === '}')
                braceCount--;
            endIdx = i;
        }
        const funcBody = src.slice(startIdx, endIdx);
        const funcLines = funcBody.split('\n').length;
        if (funcLines > 60) {
            const line = lineOf(funcMatch.index ?? 0);
            ocorrencias.push(warn(messages.GoMensagens.longFunction, relPath, line));
        }
    }
    for (const match of scan.matchAll(/^var\s+\w+\s+(?:[a-zA-Z]+\s*=\s*|$)/gm)) {
        const line = lineOf(match.index);
        ocorrencias.push(warn(messages.GoMensagens.globalVar, relPath, line));
    }
    for (const match of scan.matchAll(/\breturn\b(?!\s+\w)/gm)) {
        const line = lineOf(match.index);
        const srcBefore = src.slice(0, match.index);
        const funcMatch = srcBefore.match(/\bfunc\s+\w+\s*\([^)]*\)\s*\(([^)]*)\)/);
        if (funcMatch && funcMatch[1]?.trim()) {
            const snippet = src.slice(match.index, match.index + 50);
            if (!snippet.includes('return ') || /^return\s*$/.test(snippet.trim())) {
                ocorrencias.push(warn('Naked return in function with named return values; prefer explicit returns', relPath, line, messages.SeverityNiveis.suggestion));
            }
        }
    }
    for (const match of scan.matchAll(/\b(err\w*)\s*:?=\s*(?:fmt|errors)\.(Errorf|New)\(/g)) {
        const varName = match[1];
        if (varName !== 'err' && !varName.startsWith('err')) {
            const line = lineOf(match.index);
            ocorrencias.push(warn(`Error variable '${varName}' should follow 'err' naming convention`, relPath, line, messages.SeverityNiveis.suggestion));
        }
    }
    return ocorrencias;
}
export const analistaGoBoasPraticas = criarAnalista({
    nome: 'analista-go-boas-praticas',
    categoria: 'boas-praticas',
    descricao: 'Detecta desvios de boas práticas em código Go.',
    global: false,
    test: (relPath) => /\.go$/i.test(relPath),
    aplicar: async (src, relPath) => {
        if (disableEnv)
            return null;
        const msgs = collectBestPractices(src, relPath);
        return msgs.length ? msgs : null;
    }
});
//# sourceMappingURL=analyst-best-practices.js.map