const { app, BrowserWindow, dialog, ipcMain } = require("electron");
const path = require("path");
const fs = require("fs");
const { spawn } = require("child_process");

let mainWindow;
let deployProcess = null;

function getAppRoot() {
  return app.getAppPath();
}

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 460,
    height: 760,
    minWidth: 420,
    minHeight: 680,
    backgroundColor: "#111820",
    title: "Deploy Master",
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
      contextIsolation: true,
      nodeIntegration: false
    }
  });

  mainWindow.setMenuBarVisibility(false);
  mainWindow.loadFile(path.join(__dirname, "renderer", "index.html"));
}

function readTargets() {
  const targetsPath = path.join(getAppRoot(), "targets.json");
  const content = fs.readFileSync(targetsPath, "utf8");
  const config = JSON.parse(content);
  return Array.isArray(config.targets)
    ? config.targets.map(target => ({
        id: target.id,
        name: target.name,
        host: target.host,
        port: target.port,
        remoteAppPath: target.remoteAppPath
      }))
    : [];
}

function sendDeployEvent(payload) {
  if (mainWindow && !mainWindow.isDestroyed()) {
    mainWindow.webContents.send("deploy:event", payload);
  }
}

app.whenReady().then(createWindow);

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

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

ipcMain.handle("targets:list", () => readTargets());

ipcMain.handle("dialog:zip", async (_, options = {}) => {
  const result = await dialog.showOpenDialog(mainWindow, {
    title: options.title || "Seleccionar ZIP",
    properties: ["openFile"],
    filters: [{ name: "ZIP", extensions: ["zip"] }]
  });

  if (result.canceled || result.filePaths.length === 0) return null;
  return result.filePaths[0];
});

ipcMain.handle("deploy:start", async (_, payload) => {
  if (deployProcess) {
    throw new Error("Ya hay un deploy en ejecucion.");
  }

  const version = String(payload.version || "").trim();
  const zipPath = String(payload.zipPath || "").trim();
  const reportsZipPath = String(payload.reportsZipPath || "").trim();
  const targetId = String(payload.targetId || "").trim();

  if (!version) throw new Error("Completa el numero de version.");
  if (!zipPath) throw new Error("Selecciona el archivo GT_ARIES.zip.");
  if (!targetId) throw new Error("Selecciona un destino.");

  const scriptPath = path.join(getAppRoot(), "deploy.ps1");
  const targetsPath = path.join(getAppRoot(), "targets.json");
  const args = [
    "-NoProfile",
    "-ExecutionPolicy",
    "Bypass",
    "-File",
    scriptPath,
    "-Version",
    version,
    "-ZipPath",
    zipPath,
    "-TargetId",
    targetId,
    "-TargetsPath",
    targetsPath
  ];

  if (reportsZipPath) {
    args.push("-ReportsZipPath", reportsZipPath);
  }

  sendDeployEvent({ type: "started" });

  deployProcess = spawn("powershell.exe", args, {
    cwd: getAppRoot(),
    windowsHide: true
  });

  deployProcess.stdout.on("data", chunk => {
    sendDeployEvent({ type: "stdout", text: chunk.toString() });
  });

  deployProcess.stderr.on("data", chunk => {
    sendDeployEvent({ type: "stderr", text: chunk.toString() });
  });

  deployProcess.on("error", error => {
    sendDeployEvent({ type: "error", text: error.message });
    deployProcess = null;
  });

  deployProcess.on("close", code => {
    sendDeployEvent({ type: "finished", code });
    deployProcess = null;
  });

  return { ok: true };
});

ipcMain.handle("deploy:stop", async () => {
  if (!deployProcess) return { ok: true };
  deployProcess.kill();
  deployProcess = null;
  sendDeployEvent({ type: "finished", code: -1 });
  return { ok: true };
});
