import { promises as fs } from 'node:fs';
import { fileURLToPath } from 'node:url';
function isEntry(x) {
    if (!x || typeof x !== 'object')
        return false;
    const ocorrencia = x;
    return typeof ocorrencia.nome === 'string' && typeof ocorrencia.aplicar === 'function';
}
function extrairEntradasDeModulo(mod) {
    const metrica = mod;
    const out = [];
    const candidates = [];
    candidates.push(metrica.default);
    if (Array.isArray(metrica.analistas))
        candidates.push(...metrica.analistas);
    for (const valor of Object.values(metrica))
        candidates.push(valor);
    for (const elem of candidates) {
        if (Array.isArray(elem)) {
            for (const item of elem)
                if (isEntry(item))
                    out.push(item);
            continue;
        }
        if (isEntry(elem))
            out.push(elem);
    }
    const byName = new Map();
    for (const erro of out) {
        if (erro.nome)
            byName.set(erro.nome, erro);
    }
    return Array.from(byName.values());
}
export async function discoverAnalistasPlugins() {
    try {
        const dirUrl = new URL('../plugins/', import.meta.url);
        const dirFsPath = fileURLToPath(dirUrl);
        const entries = await fs.readdir(dirFsPath, {
            withFileTypes: true
        });
        const arquivos = entries.filter(erro => erro.isFile()).map(erro => erro.name).filter(node => node !== 'index.ts' && node !== 'index.js').filter(node => /^(analista|detector)-.+\.(ts|js)$/i.test(node));
        const results = [];
        for (const fname of arquivos) {
            try {
                const fileUrl = new URL(fname, dirUrl);
                const mod = (await import(fileUrl.toString()));
                const extracted = extrairEntradasDeModulo(mod);
                results.push(...extracted);
            }
            catch {
            }
        }
        const byName = new Map();
        for (const raiz of results) {
            const entry = raiz;
            if (entry?.nome)
                byName.set(entry.nome, raiz);
        }
        return Array.from(byName.values());
    }
    catch {
        return [];
    }
}
//# sourceMappingURL=autodiscovery.js.map