/**
 * @author Taoya
 * @date 2022/5/23
 * @Description: 构建开发环境包
 */
import * as fs from 'fs';
import { resolve } from 'path';
import { exec, ChildProcess } from 'child_process';
import chalk from 'chalk';
import logger from 'consola'

interface BuildResult {
  success: boolean;
  message: string;
}

async function buildAndroid(): Promise<BuildResult> {
  return new Promise((resolve) => {
    const buildProcess = exec('npx cordova run android', (error, stdout, stderr) => {
      if (error) {
        resolve({
          success: false,
          message: error.message
        });
        return;
      }

      if (stdout.includes('BUILD SUCCESSFUL')) {
        resolve({
          success: true,
          message: 'BUILD SUCCESSFUL'
        });
      } else {
        resolve({
          success: false,
          message: stderr || '构建失败'
        });
      }
    });

    // 输出构建日志
    buildProcess.stdout?.on('data', (data: string) => {
      console.log(chalk.green(data));
    });
  });
}

async function main(): Promise<void> {
  try {
    const packageName: string = 'dev.apk';
    const distPath: string = './dist';
    const outputPath: string = './platforms/android/app/build/outputs/apk/debug/app-debug.apk';

    // 检查dist目录是否存在，不存在则创建
    if (!fs.existsSync(distPath)) {
      fs.mkdirSync(distPath, { recursive: true });
    }

    // 构建android应用
    const buildResult = await buildAndroid();

    if (buildResult.success) {
      logger.log('info', '构建成功');

      // 如果目标文件已存在则删除
      if (fs.existsSync(`${distPath}/${packageName}`)) {
        fs.unlinkSync(`${distPath}/${packageName}`);
      }

      // 移动构建产物
      fs.renameSync(outputPath, `${distPath}/${packageName}`);
    } else {
      logger.log('error', `构建失败: ${buildResult.message}`);
      process.exit(1);
    }
  } catch (error) {
    logger.log('error', `执行失败: ${error instanceof Error ? error.message : '未知错误'}`);
    process.exit(1);
  }
}

// 执行主函数
main().catch(error => {
  logger.log('error', `意外错误: ${error instanceof Error ? error.message : '未知错误'}`);
  process.exit(1);
});