import type { RsbuildPlugin } from '@rsbuild/core';
import archiver from 'archiver';
import { createWriteStream, existsSync } from 'fs';
import { rm } from 'fs/promises';

export function zipDistPlugin(distPath: string): RsbuildPlugin {
  return {
    name: 'zip-dist-plugin',
    setup(api) {
      api.onAfterBuild(async () => {
        // 从 process.env 获取环境信息
        const isProd = process.env.NODE_ENV === 'production';

        // 只在生产环境构建时打包
        if (!isProd) {
          return;
        }
        const zipPath = `${distPath}.zip`;

        console.log(`\n📦 正在打包 ${distPath} 为 ${zipPath}...`);

        // 检查目录是否存在
        if (!existsSync(distPath)) {
          console.error(`❌ 目录不存在: ${distPath}`);
          return;
        }

        return new Promise((resolve, reject) => {
          const output = createWriteStream(zipPath);
          const archive = archiver('zip', {
            zlib: { level: 9 }, // 最高压缩级别
          });

          output.on('close', async () => {
            const MB = (archive.pointer() / 1024 / 1024).toFixed(2);
            console.log(`✅ 打包完成: ${zipPath} (${MB} MB)`);

            // 删除原始目录
            try {
              await rm(distPath, { recursive: true, force: true });
              console.log(`🗑️  已删除原始目录: ${distPath}\n`);
            } catch (err) {
              console.error(`⚠️  删除目录失败: ${distPath}`, err);
            }

            resolve();
          });

          archive.on('error', (err) => {
            console.error('❌ 打包失败:', err);
            reject(err);
          });

          archive.pipe(output);
          archive.directory(distPath, false);
          archive.finalize();
        });
      });
    },
  };
}
