const ROOT = process.cwd();
const fs = require('fs');
const path = require('path');
const exec = require('child_process').spawnSync;

console.log('[biliSapp - info] 开始检查编译工具版本（若特殊场景需忽略工具更新，请使用「npm run build mid=xxx ignore_tool_check」）');

let _npm = /^win/.test(process.platform) ? 'npm.cmd' : 'npm';
// package.json 中的 small-app 的版本号
let packageSapp = ''
    // 本地安装的small-app的版本号（包含：安装、没有安装）
let localSappVersion = ''
    // 远端的small-app的版本号最新
let serveSappVersion = ''
    // 远端的small-app的所有tag号
let serveSappAllTags = ''
    // 本地安装 bili-small-app 的信息
let localSapp = {};

// 检查本地 small-app版本号
const packageJson = fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8');

try {
    const _packageJson = JSON.parse(packageJson);
    packageSapp = _packageJson.dependencies['bili-small-app'];
} catch (e) {
    console.log('[biliSapp - warn]:检测到当前小程序未安装「 bili-small-app 」。')
}

console.log('[biliSapp - info] 本地用户指定编译工具版本：', packageSapp);

if (!/^file:/.test(packageSapp)) {

    // 检查远端 small-app版本号
    try {
        const serveJSON = exec(_npm, ['view', 'bili-small-app', '--json']).stdout.toString();
        serveSappVersion = JSON.parse(serveJSON).version;
        serveSappAllTags = JSON.parse(serveJSON)['dist-tags'];
    } catch (e) {
        console.log('[biliSapp - warn]:', '检查「 bili-small-app 」最新版本失败，请在控制台检查「 npm view bili-small-app 」命令是否可用')
    }

    try {
        localSapp = JSON.parse(exec(_npm, ['list', 'bili-small-app', '--json']).stdout.toString());
        localSappVersion = localSapp.dependencies['bili-small-app'].version;
    } catch (e) {
        console.log('[biliSapp - warn]:', '检查「 bili-small-app 」本地安装版本失败，请在控制台检查「 npm list bili-small-app 」命令是否可用')
    }

    const isTagBySapp = !!serveSappAllTags[packageSapp]
    const _isTagByLocal = serveSappAllTags[packageSapp] !== localSappVersion

    const _newVersion = isTagBySapp ? serveSappAllTags[packageSapp] : serveSappVersion;
    const _reallyVersion = localSappVersion || '未安装';

    if (_newVersion === _reallyVersion) {
        console.log('[biliSapp - info] 编译工具已安装最新版本');
    } else {
        console.log('[biliSapp - info] 远端编译工具最新版本：', isTagBySapp ? serveSappAllTags[packageSapp] : serveSappVersion);
        console.log('[biliSapp - info] 实际安装编译工具版本：', localSappVersion || '未安装');
        if (!isTagBySapp) {
            console.log('[biliSapp - info] 编译工具更新中...');

            const _execResult = exec(_npm, ['i', 'bili-small-app@latest'], {
                cwd: path.join(ROOT, './')
            })
            if (_execResult.status === 0) {
                console.log('[biliSapp - info] 编译工具更新成功（若无法拉取到最新版本，请等待5-10分钟，等待npm缓存更新）');

                try {
                    localSapp = JSON.parse(exec(_npm, ['list', 'bili-small-app', '--json']).stdout.toString());
                    localSappVersion = localSapp.dependencies['bili-small-app'].version;
                } catch (e) {
                    console.log('[biliSapp - warn]:', '检查「 bili-small-app 」本地安装版本失败，请在控制台检查「 npm list bili-small-app 」命令是否可用')
                }

                console.log('[biliSapp - info] 已安装编译工具版本：', localSappVersion);
            } else {
                console.log(`[biliSapp - info] 编译工具更新失败，请在控制台确认命令「npm i bili-small-app@latest」命令是否可用`);
            }

            let temp = JSON.parse(packageJson);
            temp.dependencies['bili-small-app'] = 'latest';

            fs.writeFileSync(path.join(ROOT, 'package.json'), JSON.stringify(temp, undefined, '\t'), 'utf8');

        } else {
            if (_isTagByLocal) {
                console.log('[biliSapp - info] 编译工具更新中...');
                const _execResult = exec(_npm, ['i', `bili-small-app@${packageSapp}`], {
                    cwd: path.join(ROOT, './')
                })
                if (_execResult.status === 0) {
                    console.log('[biliSapp - info] 编译工具更新成功（若无法拉取到最新版本，请等待5-10分钟，等待npm缓存更新）');

                    try {
                        localSapp = JSON.parse(exec(_npm, ['list', 'bili-small-app', '--json']).stdout.toString());
                        localSappVersion = localSapp.dependencies['bili-small-app'].version;
                    } catch (e) {
                        console.log('[biliSapp - warn]:', '检查「 bili-small-app 」本地安装版本失败，请在控制台检查「 npm list bili-small-app 」命令是否可用')
                    }

                    console.log('[biliSapp - info] 已安装编译工具版本：', localSappVersion);
                } else {
                    console.log(`[biliSapp - info] 编译工具更新失败，请在控制台确认命令「npm i bili-small-app@${packageSapp}」`);
                }

                let temp = JSON.parse(packageJson);
                temp.dependencies['bili-small-app'] = packageSapp;

                fs.writeFileSync(path.join(ROOT, 'package.json'), JSON.stringify(temp, undefined, '\t'), 'utf8');
            }
            if (packageSapp !== 'latest') {
                console.log('[biliSapp - warn] 当前是开发版，上线前请替换「bili-small-app」的版本为「latest」');
            }
        }
    }
}