import { join } from 'node:path';
import { readdir, readFile } from 'node:fs/promises';
import { exec } from 'node:child_process';

export const getGlobalModules = () => new Promise((resolve, reject) => {
    exec('npm root -g', async (err, stdout) => {
        if (err) {
            return reject(err);
        }
        const nodeModules = stdout.trim();
        const moduleDirs = [];
        const dirs = await readdir(nodeModules, { withFileTypes: true });
        for (const dir of dirs) {
            if (dir.isDirectory()) {
                if (dir.name[0] === '@') {
                    const innerDirs = await readdir(join(nodeModules, dir.name), { withFileTypes: true });
                    for (const innerDir of innerDirs) {
                        if (innerDir.isDirectory) {
                            moduleDirs.push(join(nodeModules, dir.name, innerDir.name));
                        }
                    }
                } else {
                    moduleDirs.push(join(nodeModules, dir.name));
                }
            }
        }
        const moduleMetas = await Promise.all(moduleDirs.map(async dir => {
            try {
                const pkg = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8'));
                return { dir, pkg };
            } catch { return undefined; }
        }));
        return resolve(moduleMetas.filter(v=>!!v));
    });
});
