import { defineConfig } from 'vite';
import { resolve } from 'path';
import fs from 'fs';
import path from 'path';
____plugin-react____
// 检查是否已经编译过
function hasBeenCompiled() {
  const outDir = resolve(process.cwd(),'..');
  return fs.existsSync(outDir) && fs.existsSync(path.join(outDir, 'windows'));
}
// 主进程函数编译插件
function mainProcessCompiler() {
  return {
    name: 'main-process-compiler',
    
    // 开发服务器启动前触发
    configureServer(server:any) {
      // 检查是否需要编译
      if (!hasBeenCompiled()) {
        console.log('No compilation output detected, please run npm run dev:compile first');
        process.exit(1);
      }
      // 服务器启动后保存地址信息
      server.httpServer.once('listening', () => {
        const address = server.httpServer.address();
        let serverUrl = '';
        
        if (typeof address === 'string') {
          serverUrl = address;
        } else {
          // 修复 IPv6 地址处理
          let host = 'localhost';  // 默认使用 localhost
          // 只有当地址不是回环地址时才使用实际地址
          if (address.address !== '::' && address.address !== '::1' && address.address !== '0.0.0.0' && address.address !== '127.0.0.1') {
            host = address.address;
          }
          const port = address.port;
          serverUrl = `http://${host}:${port}`;
        }
        // 确保 out/main 目录存在
        const mainDir = resolve(process.cwd(),'..', 'main');
        if (!fs.existsSync(mainDir)) {
          fs.mkdirSync(mainDir, { recursive: true });
        }
        
        // 将服务器 URL 保存到文件
        const serverInfoPath = resolve(mainDir, 'dev-server.json');
        fs.writeFileSync(
          serverInfoPath, 
          JSON.stringify({ 
            url: serverUrl, 
            timestamp: new Date().toISOString(),
            isDev: true
          }, null, 2),
          'utf-8'
        );
        console.log(`The server information has been saved to: ${serverInfoPath}`);
      });
    }
  };
}

export default defineConfig(({ mode }) => {
  const isProd = mode === 'production';
  return {
  plugins: [
    react(),
    {
      name: 'adjust-asset-paths',
      transformIndexHtml(html, ctx) {
        // 获取当前 HTML 文件相对于 windows 目录的深度
        const relativePath = path.relative(__dirname, ctx.filename);
        // 额外增加两个层级
        const depth = relativePath.split(path.sep).length + 1;
        
        // 根据深度生成相对路径前缀
        const prefix = '../'.repeat(depth);
        // 替换资源引用路径
        return html.replace(/(src|href)="\/assets\//g, `$1="${prefix}assets/`)
                  .replace(/(src|href)="\/js\//g, `$1="${prefix}js/`);
      }
    },
    // 只在开发模式下使用主进程编译插件
    ...(isProd ? [] : [mainProcessCompiler()]),
  ],
  build: {
    base: './',
    emptyOutDir: false,
    // 针对 Electron 环境调整构建配置
    rollupOptions: {
      output: {
				dir:'./dist'
			},
      // 排除 electron 相关模块和HTML文件中引用的脚本
      external: [
        'electron', 
        'path', 
        'fs', 
        'os',
        // 排除HTML文件中引用的脚本
        /^\.\/main\.js$/,
        /^\.\.\/utils\/api\/github\.js$/,
        // Vue 和 Vue Router 不需要打包，由应用自己提供
        // 'vue',
        // 'vue-router'
      ],
    },
    // 减少打包大小，因为 Electron 已经包含 Node.js 环境
    commonjsOptions: {
      transformMixedEsModules: true,
    },
    // 使用旧版浏览器兼容性配置
    target: 'es2015', 
    cssTarget: 'chrome118', // 适配 Electron 28
    minify: isProd ? 'terser' : false, // 开发模式不压缩，生产模式使用 terser
    terserOptions: isProd ? {
      compress: {
        drop_console: false, // 在生产环境保留控制台日志，方便调试
        drop_debugger: true
      }
    } : undefined,
  },
  // 解析配置
  resolve: {
    alias: {
      '@': resolve(__dirname, './'),
      '@windows': resolve(__dirname, './windows'),
      '@components': resolve(__dirname, './components'),
      '@utils': resolve(__dirname, './utils'),
    }
  },
  optimizeDeps: {
    // 在生产环境中禁用依赖优化，避免冲突
    disabled: isProd
  }
}}); 