import { app } from "electron";
import { join } from "path";
import { existsSync } from "fs";

// ─── Single Instance Lock ────────────────────────
export function checkSingleInstance(): boolean {
  const gotLock = app.requestSingleInstanceLock();
  if (!gotLock) {
    app.quit();
    return false;
  }

  app.on("second-instance", (_event, _argv, _cwd) => {
    const windows = require("electron").BrowserWindow.getAllWindows();
    if (windows.length > 0) {
      const win = windows[0];
      if (win.isMinimized()) win.restore();
      win.focus();
    }
  });

  return true;
}

// ─── Dev mode detection ──────────────────────────
export function isDev(): boolean {
  return !app.isPackaged;
}

// ─── Web URL ─────────────────────────────────────
export function getWebUrl(dev: boolean, port: number): string {
  if (dev) {
    return "http://localhost:" + port;
  }

  const appPath = app.isPackaged
    ? join(process.resourcesPath, "web")
    : join(__dirname, "..", "..", "web", "out");

  const staticIndex = join(appPath, "index.html");
  if (existsSync(staticIndex)) {
    return staticIndex;
  }

  const standalone = join(appPath, ".next", "standalone", "server.js");
  if (existsSync(standalone)) {
    return "http://localhost:3000";
  }

  const fallback = join(appPath, "index.html");
  if (existsSync(fallback)) {
    return fallback;
  }

  console.warn("[utils] No web build found at", appPath);
  return "http://localhost:3000";
}

// ─── API Path ────────────────────────────────────
export function getApiPath(): string | null {
  if (app.isPackaged) {
    const packed = join(process.resourcesPath, "api", "dist", "index.js");
    if (existsSync(packed)) return packed;
    const packedSrc = join(process.resourcesPath, "api", "src", "index.js");
    if (existsSync(packedSrc)) return packedSrc;
  }

  const devPath = join(__dirname, "..", "..", "api", "dist", "index.js");
  if (existsSync(devPath)) return devPath;

  const devSrc = join(__dirname, "..", "..", "api", "src", "index.js");
  if (existsSync(devSrc)) return devSrc;

  return null;
}

// ─── Get API port from env ───────────────────────
export function getApiPort(): number {
  return 3001;
}
