import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
import WindiCSS from "vite-plugin-windicss";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import { resolve } from "path";
import fs from "fs-extra";

export default defineConfig(({ command, mode }) => {
  const { VITE_TCB_PATH,VITE_API_URL } = loadEnv(mode, process.cwd());

  return {
    base: `/${VITE_TCB_PATH}/`, //相对路径
    server: {
      host: "0.0.0.0",
      port: "5173",
      headers: {
        // 防止点击劫持攻击
        'X-Frame-Options': 'SAMEORIGIN', // 只允许同源页面嵌入
        // 'X-Frame-Options': 'DENY', // 如果要完全禁止被嵌入，使用 DENY
        // 额外的安全响应头
        'X-Content-Type-Options': 'nosniff',
        'X-XSS-Protection': '1; mode=block',
        'Content-Security-Policy': "frame-ancestors 'self'", // CSP 的现代替代方案
      },
      proxy: {
        // 将 VITE_PROXY_API_URL 的请求代理到 VITE_API_URL
        '/API': {
          target: VITE_API_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/API/, '') // 可选：重写路径
        }
      }
    },
    plugins: [
      vue(),
      WindiCSS(),
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), "src/assets/svg-icons")],
        // 指定symbolId格式
        symbolId: "icon-[dir]-[name]",
      }),
    ],
    optimizeDeps: {
      exclude: ["lib-generate-test-usersig-es.min"],
    },
    build: {
      outDir: `package/${VITE_TCB_PATH}`,
      target: ["chrome52"],
      cssTarget: ["chrome52"],
      terserOptions: {
        compress: {
          drop_console: true, // 去除 console.log 等调试信息
        },
      },
      cssCodeSplit: true, // 分割 CSS，避免全局 CSS 被打包成一个大文件
      minify: "terser", // 使用 terser 进行压缩
      brotliSize: true,
    },
    resolve: {
      //文件系统路径的别名, 绝对路径
      alias: {
        "@": path.resolve(__dirname, "src"),
      },
      extensions: [".js", ".ts", ".vue", ".json"],
    },
  };
});

async function copyOldFiles(name) {
  const srcDir = resolve(__dirname, name);
  const destDir = resolve(__dirname, `oldFile`);
  // 创建目标目录
  if (!fs.existsSync(srcDir)) {
    fs.mkdirSync(srcDir, { recursive: true });
  }
  if (!fs.existsSync(destDir)) {
    fs.mkdirSync(destDir, { recursive: true });
  }
  try {
    // 复制文件
    await fs.copy(srcDir, destDir);
  } catch (err) {}
}
