import { analistaGithubActions, analistaGithubActionsGlobal, pontuarWorkflow } from '../../../analysts/github-actions/index.js';
import { GithubWebhookMensagens, messages } from '../../../core/messages/index.js';
import { HTTP_NOT_FOUND } from './octokit.js';
const DEFAULT_SCORE = 100;
function normalizarOcorrencias(result) {
    if (!result)
        return [];
    return Array.isArray(result) ? result : [result];
}
export async function buscarWorkflows(octokit, owner, repo, ref) {
    try {
        const response = await octokit.request('GET /repos/{owner}/{repo}/contents/{path}', {
            owner,
            repo,
            path: '.github/workflows',
            ref
        });
        if (Array.isArray(response.data)) {
            return response.data
                .filter((file) => file.name.endsWith('.yml') || file.name.endsWith('.yaml'))
                .map((file) => ({ name: file.name, path: file.path }));
        }
    }
    catch (err) {
        const error = err;
        if (error.status !== HTTP_NOT_FOUND) {
            messages.log.erro(GithubWebhookMensagens.erroListarWorkflows(owner, repo, ref));
            throw err;
        }
    }
    return [];
}
export async function analisarWorkflows(octokit, owner, repo, ref, workflows) {
    const arquivosCtx = [];
    const todasOcorrencias = [];
    const workflowsInfo = [];
    let somaScores = 0;
    for (const wf of workflows) {
        const fileContentResp = await octokit.request('GET /repos/{owner}/{repo}/contents/{path}', {
            owner,
            repo,
            path: wf.path,
            ref,
            headers: { accept: 'application/vnd.github.v3.raw' }
        });
        const conteudo = fileContentResp.data;
        const relPath = wf.path;
        arquivosCtx.push({ relPath, content: conteudo });
        const result = await analistaGithubActions.aplicar(conteudo, relPath, null, undefined, {
            arquivos: arquivosCtx
        });
        const ocorrencias = normalizarOcorrencias(result);
        const scoreResult = pontuarWorkflow(conteudo, relPath);
        workflowsInfo.push({ nome: wf.name, score: scoreResult.percentage, ocorrencias: ocorrencias.length });
        todasOcorrencias.push(...ocorrencias);
        somaScores += scoreResult.percentage;
    }
    if (workflows.length > 0) {
        const resultGlobal = await analistaGithubActionsGlobal.aplicar('', '', null, undefined, {
            arquivos: arquivosCtx
        });
        todasOcorrencias.push(...normalizarOcorrencias(resultGlobal));
    }
    const scoreGeral = workflows.length > 0 ? Math.round(somaScores / workflows.length) : DEFAULT_SCORE;
    return { ocorrencias: todasOcorrencias, scoreGeral, workflowsInfo };
}
//# sourceMappingURL=workflow-reader.js.map