// Simple script for technicians to run
const { execSync } = require("child_process");
const fs = require("fs");
const os = require("os");
const readline = require("readline");

console.log(`
🎯 SIRAYA PRINTER - FIELD TECHNICIAN DEPLOYMENT
================================================
`);

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const questions = [
  {
    text: "Business Name:",
    default: "SIRAYA",
    key: "BUSINESS_NAME",
  },
  {
    text: "Phone Number:",
    default: "0325-4410555",
    key: "BUSINESS_PHONE",
  },
  {
    text: "Website:",
    default: "pos.siraya.food",
    key: "BUSINESS_WEBSITE",
  },
];

const answers = {};

const askQuestion = (index) => {
  if (index >= questions.length) {
    rl.close();
    deploy();
    return;
  }

  const q = questions[index];
  rl.question(`${q.text} [${q.default}]: `, (answer) => {
    answers[q.key] = answer || q.default;
    askQuestion(index + 1);
  });
};

const deploy = () => {
  console.log("\n🚀 Deploying printer service...");

  // Create .env file
  const envContent = `
BUSINESS_NAME=${answers.BUSINESS_NAME}
BUSINESS_PHONE=${answers.BUSINESS_PHONE}
BUSINESS_WEBSITE=${answers.BUSINESS_WEBSITE}
BUSINESS_TAGLINE=Broast . Burgers . Fries
PORT=5000
  `;

  fs.writeFileSync(".env", envContent);

  // Install dependencies
  console.log("📦 Installing dependencies...");
  try {
    execSync("npm install --production", { stdio: "inherit" });
  } catch (e) {
    console.log("⚠️ npm install failed, trying with --legacy-peer-deps");
    execSync("npm install --production --legacy-peer-deps", {
      stdio: "inherit",
    });
  }

  // Start service
  console.log("🚀 Starting service...");

  if (os.platform() === "win32") {
    // Windows
    execSync("node install-service.js", { stdio: "inherit" });
  } else {
    // Linux/Mac
    console.log("\nFor Linux/Mac, run:");
    console.log("sudo bash install.sh");
    console.log("\nOr run manually:");
    console.log("1. sudo node install-service.js");
    console.log("2. node index.js");

    // Try to start without sudo
    try {
      execSync("node index.js", { stdio: "inherit" });
    } catch (e) {
      console.log("\n⚠️ Could not start service. Try with sudo.");
    }
  }
};

askQuestion(0);
