import { obterConfigInstalacao } from '../app/installation-store.js';
import { statsStore } from '../dashboard/stats-store.js';
import { rodarAnaliseCodigo } from './analysis-core.js';
import { gerarComentarioPrAnalise, gerarCorpoPrAnalise, gerarRelatorioMarkdown, gerarResumoReviewPr } from './push-report.js';
const MAX_REVIEW_COMMENTS = 40;
const PREFIXO_BRANCH_RELATORIO = 'tutanus/';
async function publicarReviewComentarios(octokit, owner, repo, prNumber, commitId, ocorrencias) {
    const comentarios = ocorrencias
        .filter(o => o.relPath && o.linha && o.linha > 0)
        .slice(0, MAX_REVIEW_COMMENTS)
        .map(o => ({
        path: o.relPath,
        line: o.linha,
        body: `**${rotuloSeveridade(o.nivel)}** · ${o.tipo || 'geral'}\n\n${o.mensagem}${o.sugestao ? `\n\n**Sugestão:** ${o.sugestao}` : ''}`
    }));
    if (comentarios.length === 0)
        return;
    try {
        await octokit.request('POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews', {
            owner,
            repo,
            pull_number: prNumber,
            commit_id: commitId,
            event: 'COMMENT',
            body: gerarResumoReviewPr(ocorrencias.length, comentarios.length),
            comments: comentarios
        });
    }
    catch (err) {
        const { GithubWebhookMensagens } = await import('../../../core/messages/index.js');
        const { messages: msgs } = await import('../../../core/messages/index.js');
        msgs.log.aviso(GithubWebhookMensagens.reviewCommentsNoPR(err instanceof Error ? err.message : String(err)));
    }
}
function rotuloSeveridade(nivel) {
    const nivelNormalizado = (nivel || 'info').toLowerCase();
    if (nivelNormalizado === 'erro')
        return 'Erro';
    if (nivelNormalizado === 'aviso')
        return 'Aviso';
    return 'Info';
}
export async function executarAnalisePullRequest(app, params) {
    if (params.headRef.startsWith(PREFIXO_BRANCH_RELATORIO))
        return;
    const config = obterConfigInstalacao(params.installationId);
    if (!config.pullRequestAnalysisEnabled)
        return;
    const { resultado, ctx, cleanup } = await rodarAnaliseCodigo(app, {
        installationId: params.installationId,
        owner: params.owner,
        repo: params.repo,
        headSha: params.headSha,
        branch: params.headRef,
        commitMessage: params.prTitle,
        baseSha: params.baseSha,
        incremental: config.incrementalOnPush
    });
    const octokit = await app.getInstallationOctokit(params.installationId);
    try {
        const ctxPr = { ...ctx, baseRef: params.baseRef, prNumber: params.prNumber };
        const relatorioCompleto = gerarRelatorioMarkdown(resultado, ctxPr);
        const corpoAnalise = gerarCorpoPrAnalise(resultado, ctxPr);
        await octokit.request('PATCH /repos/{owner}/{repo}/pulls/{pull_number}', {
            owner: params.owner,
            repo: params.repo,
            pull_number: params.prNumber,
            body: corpoAnalise
        });
        await octokit.request('POST /repos/{owner}/{repo}/issues/{issue_number}/comments', {
            owner: params.owner,
            repo: params.repo,
            issue_number: params.prNumber,
            body: gerarComentarioPrAnalise(resultado, ctxPr, relatorioCompleto)
        });
        await publicarReviewComentarios(octokit, params.owner, params.repo, params.prNumber, params.headSha, resultado.ocorrencias);
        statsStore.recordAnalysis({
            repository: `${params.owner}/${params.repo}`,
            event: 'pull_request',
            score: resultado.scoreGeral,
            workflowsCount: 0,
            occurrencesCount: resultado.totalOcorrencias
        });
    }
    finally {
        cleanup();
    }
}
//# sourceMappingURL=pr-analysis-service.js.map