import { loadConfig } from "./config.js";
import log4js from "log4js";
import { createElectronWindow } from "./electron/window.js";
import { setupIPC } from "./electron/ipc.js";
import { SocketClient } from "./socket/socketclient.js";

// Load configuration
const config = loadConfig();

const logger = log4js.getLogger("App");
logger.level = config.logLevel;

const isHeadless = process.argv.includes("--headless");

export async function init() {
  if (!isHeadless) {
    // Create Electron window first
    logger.info("Creating electron window...");
    await createElectronWindow().catch((err) => {
      logger.warn("Failed to create Electron window:", err);
    });

    // Setup IPC communication after window is created
    setupIPC().catch((err) => {
      logger.warn("Failed to setup IPC:", err);
    });
  } else {
    logger.info("Running in headless mode. Skipping window creation.");
  }

  const socketClient = new SocketClient();
  // Make socket client globally accessible for IPC handlers
  global.socketClient = socketClient;
  socketClient.connect();

  process.on("SIGINT", () => {
    logger.info("Shutting down...");
    socketClient.disconnect();
    process.exit(0);
  });
}

init();
