import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
const fs = require('fs');
const path = require('path');
const { shell } = require('electron');

// Custom APIs for renderer
// 自定义的主进程方法API
// const api = {
//   readFile: async (path) => {
//     const result = await ipcRenderer.invoke('readFile', path);
//     return result;
//   },
//   writeFile: async (path, content) => {
//     await ipcRenderer.invoke('writeFile', path, content);
//   },
//   readDirectory: async (directoryPath) => {
//     const result = await ipcRenderer.invoke('readDirectory', directoryPath);
//     return result;
//   }
// }
// // 暴露获取版本号的方法
// ipcMain.handle('get-app-version', () => {
//   return app.getVersion(); // 返回当前应用版本（来自 package.json）
// });

// 获取config.js的绝对路径
function getConfigPath() {
  // __dirname 是 win-unpacked/resources/app

  let configPath = path.resolve('./resources/app.asar.unpacked/resources/config/config.js');
		//单独配置测试环境
		if (process.env.NODE_ENV === 'development') {
			configPath = path.resolve('./resources/config/config.js');
		}

  return configPath;
}

function getExportPath() {
  // __dirname 是 win-unpacked/resources/app

  let configPath = path.resolve('./resources/app.asar.unpacked/resources/service');
		//单独配置测试环境
		if (process.env.NODE_ENV === 'development') {
			configPath = path.resolve('./resources/service');
		}

  return configPath;
}


// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
// 使用contextBridge将Electron API和自定义的主进程方法API暴露给渲染进程页面。
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', {
      ...electronAPI,
      getAppVersion: async () => {
        return await ipcRenderer.invoke('get-app-version');
      },
      readConfig: () => {
        const configPath = getConfigPath();
        if (fs.existsSync(configPath)) {
          // 用require动态加载，确保每次都是最新内容
          delete require.cache[require.resolve(configPath)];
          return require(configPath);
        }
        return {};
      },
      shell: {
        openPath: shell.openPath
      },
      exePath: getExportPath()
    })
    // contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  window.electron = {
    ...electronAPI,
    getAppVersion: async () => {
      return await ipcRenderer.invoke('get-app-version');
    },
    readConfig: () => {
      const configPath = getConfigPath();
      if (fs.existsSync(configPath)) {
        // 用require动态加载，确保每次都是最新内容
        delete require.cache[require.resolve(configPath)];
        return require(configPath);
      }
      return {};
    },
    shell: {
      openPath: shell.openPath
    },
    exePath: getExportPath()
  }
  // window.api = api
}
