import { GithubWebhookMensagens } from '../../../core/messages/index.js';
import { statsStore } from '../dashboard/stats-store.js';
import { MAX_ANNOTATIONS } from './check-run-builder.js';
import { analisarWorkflows, buscarWorkflows } from './workflow-reader.js';
const TRIGGER_TOKEN = '@tutanus analyze';
export async function processarPullRequestReview(app, payload) {
    const { repository, pull_request, review, installation, action } = payload;
    if (action !== 'submitted' || review.state !== 'commented')
        return;
    if (!installation?.id)
        return;
    const owner = repository.owner.login;
    const repo = repository.name;
    const headSha = pull_request.head.sha;
    const prNumber = pull_request.number;
    const reviewBody = (review.body || '').toLowerCase();
    if (!reviewBody.includes(TRIGGER_TOKEN))
        return;
    const octokit = await app.getInstallationOctokit(installation.id);
    try {
        await octokit.request('POST /repos/{owner}/{repo}/issues/{issue_number}/comments', {
            owner,
            repo,
            issue_number: prNumber,
            body: '[BUSCA] **Tutanus** iniciando análise dos workflows...'
        });
        const workflows = await buscarWorkflows(octokit, owner, repo, headSha);
        if (workflows.length === 0) {
            await octokit.request('POST /repos/{owner}/{repo}/issues/{issue_number}/comments', {
                owner,
                repo,
                issue_number: prNumber,
                body: GithubWebhookMensagens.nenhumWorkflow
            });
            return;
        }
        const { ocorrencias, scoreGeral, workflowsInfo } = await analisarWorkflows(octokit, owner, repo, headSha, workflows);
        statsStore.recordAnalysis({
            repository: `${owner}/${repo}`,
            event: 'pull_request_review',
            score: scoreGeral,
            workflowsCount: workflows.length,
            occurrencesCount: ocorrencias.length
        });
        const comment = renderReviewComment(scoreGeral, workflowsInfo, ocorrencias);
        await octokit.request('POST /repos/{owner}/{repo}/issues/{issue_number}/comments', {
            owner,
            repo,
            issue_number: prNumber,
            body: comment
        });
    }
    catch (err) {
        const error = err;
        await octokit.request('POST /repos/{owner}/{repo}/issues/{issue_number}/comments', {
            owner,
            repo,
            issue_number: prNumber,
            body: `Erro na análise: \`${error.message}\``
        });
    }
}
function renderReviewComment(scoreGeral, workflowsInfo, ocorrencias) {
    let comment = `## Tutanus - Análise Sob Demanda\n\n`;
    comment += `**Score Geral:** ${scoreGeral}/100\n\n`;
    for (const wf of workflowsInfo) {
        const icon = wf.score >= 80 ? '[OK]' : wf.score >= 50 ? '[AVISO]' : '[ERRO]';
        comment += `- ${icon} **${wf.nome}** (Score: ${wf.score}/100)\n`;
    }
    if (ocorrencias.length > 0) {
        comment += `\n### Ocorrências (${ocorrencias.length})\n\n`;
        for (const o of ocorrencias.slice(0, MAX_ANNOTATIONS)) {
            comment += `- **${o.nivel?.toUpperCase() || 'INFO'}**: \`${o.relPath}:${o.linha || 1}\` - ${o.mensagem}\n`;
        }
    }
    else {
        comment += `\nNenhuma ocorrência encontrada.\n`;
    }
    return comment;
}
//# sourceMappingURL=pr-review-handler.js.map