const fs = require("fs");
const os = require("os");
const path = require("path");

/** Queue + logs under ProgramData on Windows; ~/.siraya-printer elsewhere. */
function getSirayaDataRoot() {
  if (process.env.SIRAYA_DATA_DIR) {
    return path.resolve(process.env.SIRAYA_DATA_DIR);
  }
  if (process.platform === "win32") {
    const base =
      process.env.ProgramData ||
      path.join(process.env.SystemDrive || "C:", "ProgramData");
    return path.join(base, "Siraya", "Printer");
  }
  const linuxSystemData = "/var/lib/siraya/printer";
  if (
    process.platform === "linux" &&
    fs.existsSync(path.join(linuxSystemData, ".env"))
  ) {
    return linuxSystemData;
  }
  if (process.platform === "linux" && fs.existsSync(linuxSystemData)) {
    try {
      fs.accessSync(linuxSystemData, fs.constants.W_OK);
      return linuxSystemData;
    } catch {
      /* use home dir */
    }
  }
  return path.join(os.homedir(), ".siraya-printer");
}

function getPrintDataDir() {
  if (process.env.PRINT_DATA_DIR) {
    return path.resolve(process.env.PRINT_DATA_DIR);
  }
  return path.join(getSirayaDataRoot(), "queue");
}

function getLogsDir() {
  if (process.env.LOG_DIR) {
    return path.resolve(process.env.LOG_DIR);
  }
  return path.join(getSirayaDataRoot(), "logs");
}

function getConfigPath() {
  return path.join(getSirayaDataRoot(), "printer-config.json");
}

function ensureDir(dir) {
  fs.mkdirSync(dir, { recursive: true });
}

module.exports = {
  getSirayaDataRoot,
  getPrintDataDir,
  getLogsDir,
  getConfigPath,
  ensureDir,
};
