// Simple starter that works on all platforms
const { spawn } = require("child_process");
const path = require("path");
const fs = require("fs");
const os = require("os");

console.log(`
🚀 SIRAYA THERMAL PRINTER SERVICE
=================================
Starting service...
`);

// Check if service is already running
const checkPort = require("net").createServer();
checkPort.once("error", () => {
  console.log("⚠️ Port 5000 is busy. Service might already be running.");
  console.log("🌐 Open: http://localhost:5000");
});

checkPort.once("listening", () => {
  checkPort.close();

  // Start the main service
  const service = spawn("node", ["index.js"], {
    cwd: __dirname,
    stdio: "inherit",
    detached: true,
  });

  console.log("✅ Service started successfully!");
  console.log("🌐 Open: http://localhost:5000");
  console.log("📋 Press Ctrl+C to stop the service\n");

  // Auto-open browser after 3 seconds
  setTimeout(() => {
    const open = require("child_process").spawn;

    if (os.platform() === "win32") {
      open("cmd", ["/c", "start", "http://localhost:5000"]);
    } else if (os.platform() === "darwin") {
      open("open", ["http://localhost:5000"]);
    } else {
      open("xdg-open", ["http://localhost:5000"]);
    }
  }, 3000);

  // Handle process exit
  process.on("SIGINT", () => {
    console.log("\n🛑 Stopping service...");
    process.kill(-service.pid); // Kill entire process group
    process.exit();
  });
});
