import { app, BrowserWindow, ipcMain, dialog } from "electron";
import { fileURLToPath } from "url";
import path from "path";
import { execFile } from "child_process";
import fs from "fs";

process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

let mainWindow = null;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 800,
    webPreferences: {
      preload: path.join(__dirname, "./preload.mjs"),
      contextIsolation: true,
      nodeIntegration: false,
      allowRunningInsecureContent: false,
    },
  });
  //环境判断引入不同的页面
  if (process.env.NODE_ENV === "development") {
    mainWindow.loadURL("http://localhost:5173");
    mainWindow.webContents.openDevTools();
  } else {
    //生产环境将引入打包好的文件
    mainWindow.loadFile(path.join(__dirname, "../dist/index.html"));
    mainWindow.webContents.openDevTools();
  }
  // **🔹 监听渲染进程调用 Python EXE**
  ipcMain.handle("run-python-exe", async (event, apiName, params = {}) => {
    return new Promise((resolve, reject) => {
      let pythonExePath = null;
      if (process.env.NODE_ENV === "development") {
        // **开发环境**
        pythonExePath = path.join(__dirname, "../serves/dist/api_test.exe");
      } else {
        //这里需要区分开发环境还是生产环境 生产环境用到这个路径
        pythonExePath = path.join(
          process.resourcesPath, // `app.asar.unpacked` 的默认路径
          "app.asar.unpacked",
          "serves",
          "dist",
          "api_test.exe"
        );
      }
      // **修改 Python EXE 的路径**

      console.log("🔹 正在执行 Python EXE:", pythonExePath);
      if (!fs.existsSync(pythonExePath)) {
        reject(`Python EXE 不存在: ${pythonExePath}`);
        return;
      }
      // **参数列表：API 名称 + JSON 格式参数**
      const args = [apiName, JSON.stringify(params)];
      console.log("📡 调用 Python EXE:", pythonExePath, "参数:", args);
      execFile(pythonExePath, args, (error, stdout, stderr) => {
        if (error) {
          console.error("❌ Python EXE 运行失败:", error);
          reject(`Error: ${error.message}`);
          return;
        }
        if (stderr) {
          console.warn("⚠️ Python EXE 输出警告:", stderr);
        }

        // **尝试解析 JSON**
        try {
          console.log("✅ Python EXE 输出:", stdout);
          resolve(JSON.parse(stdout)); // 返回 JSON 数据
        } catch (parseError) {
          console.warn("⚠️ Python EXE 返回的不是 JSON:", stdout);
          resolve(stdout.trim()); // 返回原始文本
        }
      });
    });
  });
  // 监听 get-file-path 事件 监听渲染进程请求文件路径
  ipcMain.handle("get-file-path", async () => {
    try {
      const { filePaths } = await dialog.showOpenDialog({
        properties: ["openFile", "multiSelections"], // ✅ 允许选择多个文件
      });
      if (filePaths.length > 0) {
        console.log("用户选择的文件路径:", filePaths[0]);
        return filePaths[0]; // 返回文件路径
      } else {
        console.log("用户取消了选择");
        return null; // 用户没有选择文件
      }
    } catch (error) {
      console.error("获取文件路径失败:", error);
      return null;
    }
  });
  mainWindow.on("closed", () => {
    mainWindow = null;
  });
}

app.whenReady().then(createWindow);

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") app.quit();
});

app.on("activate", () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

export { createWindow };
