const fs = require('fs');
const path = require('path');
// const pathThreeAdapterEntry = require.resolve('./index');
const cp = require('child_process');

const adapterPath = path.resolve(__dirname, './', 'threejs-adapter');
const adapterFilePath = path.resolve(adapterPath, 'dist', 'index.js');

module.exports = function resolveThreeModule() {
    console.log('[biliSapp - info] three adapter: 请确保使用版本为「0.133.0」');
    const callback = this.async();
    process.env._threePath = process.cwd();
    fs.access(adapterFilePath, fs.F_OK, (err) => {
        if (err) {
            console.log('[biliSapp - info] three adapter: 本地无编译缓存，编译中...');
            cp.exec(`cd ${adapterPath} && npm install && npm run build`, {}, (err, stdout) => {
                // console.log(err,stdout)
                console.log('[biliSapp - info] three adapter: 编译成功');

                const code = fs.readFileSync(adapterFilePath, 'utf-8');
                callback(err, code);
            });
            return;
        }
        console.log('[biliSapp - info] three adapter: 命中编译缓存');
        const code = fs.readFileSync(adapterFilePath, 'utf-8');
        callback(err, code);
        console.log('[biliSapp - info] three adapter: 编译完成');
    });
};
