const { app, BrowserWindow, ipcMain, shell, Tray, Menu } = require("electron");
const path = require("path");
const fs = require("fs");
const os = require("os");
const { runFirstRunSetup, getServiceBundleRoot, getIconPath } = require("./installer");
const {
  getServiceStatus,
  startService,
  stopService,
  restartService,
} = require("./service-control");
const { initUpdater } = require("./updater");

let mainWindow = null;
let tray = null;
const isDev = !app.isPackaged;

function getConfigPath() {
  if (process.platform === "win32") {
    const base = process.env.ProgramData || "C:\\ProgramData";
    return path.join(base, "Siraya", "Printer", "desktop-config.json");
  }
  const xdg =
    process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
  return path.join(xdg, "siraya-printer", "desktop-config.json");
}

function loadDesktopConfig() {
  try {
    if (fs.existsSync(getConfigPath())) {
      return JSON.parse(fs.readFileSync(getConfigPath(), "utf8"));
    }
  } catch {
    /* ignore */
  }
  return { firstRunCompleted: false, serviceUrl: "http://127.0.0.1:5000" };
}

function saveDesktopConfig(cfg) {
  const dir = path.dirname(getConfigPath());
  fs.mkdirSync(dir, { recursive: true });
  fs.writeFileSync(getConfigPath(), JSON.stringify(cfg, null, 2), "utf8");
}

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1100,
    height: 760,
    minWidth: 900,
    minHeight: 600,
    title: "Siraya Printer",
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
      contextIsolation: true,
      nodeIntegration: false,
    },
    icon: getIconPath(),
  });

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

  mainWindow.on("close", (e) => {
    if (!app.isQuitting) {
      e.preventDefault();
      mainWindow.hide();
    }
  });
}

function createTray() {
  const icon = getIconPath();
  if (!icon) return;
  tray = new Tray(icon);
  const contextMenu = Menu.buildFromTemplate([
    {
      label: "Open Siraya Printer",
      click: () => {
        if (mainWindow) mainWindow.show();
      },
    },
    {
      label: "Quit",
      click: () => {
        app.isQuitting = true;
        app.quit();
      },
    },
  ]);
  tray.setToolTip("Siraya Printer Agent");
  tray.setContextMenu(contextMenu);
  tray.on("double-click", () => {
    if (mainWindow) mainWindow.show();
  });
}

async function ensureSetup() {
  const cfg = loadDesktopConfig();
  if (cfg.firstRunCompleted) {
    const st = await getServiceStatus();
    if (st.running) return cfg;
  }

  const result = await runFirstRunSetup({
    bundleRoot: getServiceBundleRoot(),
    onProgress: (msg) => {
      if (mainWindow) {
        mainWindow.webContents.send("setup-progress", msg);
      }
    },
  });
  if (result.ok) {
    cfg.firstRunCompleted = true;
    cfg.serviceUrl = result.serviceUrl || cfg.serviceUrl;
    saveDesktopConfig(cfg);
  }
  return { ...cfg, setupResult: result };
}

app.whenReady().then(async () => {
  createWindow();
  createTray();
  initUpdater(mainWindow);

  ipcMain.handle("get-config", () => loadDesktopConfig());
  ipcMain.handle("get-service-status", () => getServiceStatus());
  ipcMain.handle("service-start", () => startService());
  ipcMain.handle("service-stop", () => stopService());
  ipcMain.handle("service-restart", () => restartService());
  ipcMain.handle("run-setup", () => ensureSetup());
  ipcMain.handle("open-external", (_, url) => shell.openExternal(url));
  ipcMain.handle("get-service-url", () => loadDesktopConfig().serviceUrl);

  await ensureSetup();
});

app.on("before-quit", () => {
  app.isQuitting = true;
});

app.on("window-all-closed", (e) => {
  e.preventDefault();
});
