// config.js - Configuration handling
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import log4js from "log4js";

// Determine environment
const NODE_ENV = process.env.NODE_ENV || "development";

// Configure paths
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

function getProductionConfigPath() {
  switch (process.platform) {
    case "win32":
      return path.join(
        process.env.PROGRAMDATA || "C:\\ProgramData",
        "farmcontrol-server",
        "config.json"
      );
    case "darwin":
      // macOS standard for system-wide config is often /etc or /Library/Application Support
      // We'll stick to /etc as requested for parity with Linux
      return "/etc/farmcontrol-server/config.json";
    case "linux":
    default:
      return "/etc/farmcontrol-server/config.json";
  }
}

const CONFIG_PATH =
  NODE_ENV === "production"
    ? getProductionConfigPath()
    : path.resolve(__dirname, "../config.json");

const logger = log4js.getLogger("Config");
logger.level = "info";

const DEFAULT_CONFIG = {
  development: {
    logLevel: "debug",
    url: "https://dev-wss.tombutcher.work",
    apiUrl: "https://dev.tombutcher.work/api",
    host: {
      id: "",
      authCode: "",
    },
  },
  production: {
    logLevel: "info",
    url: "https://ws.farmcontrol.app",
    apiUrl: "https://api.farmcontrol.app",
    host: {
      id: "",
      authCode: "",
    },
  },
};

// Load config file
export function loadConfig() {
  try {
    if (!fs.existsSync(CONFIG_PATH)) {
      logger.info(
        `Configuration file not found at ${CONFIG_PATH}. Creating a new one.`
      );
      const configDir = path.dirname(CONFIG_PATH);
      if (!fs.existsSync(configDir)) {
        fs.mkdirSync(configDir, { recursive: true });
      }
      fs.writeFileSync(
        CONFIG_PATH,
        JSON.stringify(DEFAULT_CONFIG, null, 2),
        "utf8"
      );
    }

    const configData = fs.readFileSync(CONFIG_PATH, "utf8");
    const config = JSON.parse(configData);

    if (!config[NODE_ENV]) {
      throw new Error(
        `Configuration for environment '${NODE_ENV}' not found in config.json`
      );
    }

    return config[NODE_ENV];
  } catch (err) {
    logger.error("Error loading config:", err);
    throw err;
  }
}

// Save config file
export function saveConfig(newConfig) {
  try {
    logger.info("Saving...");
    let config = {};
    if (fs.existsSync(CONFIG_PATH)) {
      const configData = fs.readFileSync(CONFIG_PATH, "utf8");
      config = JSON.parse(configData);
    } else {
      const configDir = path.dirname(CONFIG_PATH);
      if (!fs.existsSync(configDir)) {
        fs.mkdirSync(configDir, { recursive: true });
      }
    }

    // Update current environment
    config[NODE_ENV] = newConfig;

    // Write back to file with 2-space indentation
    fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), "utf8");
    logger.info(`Configuration for '${NODE_ENV}' saved successfully.`);
  } catch (err) {
    logger.error("Error saving config:", err);
    throw err;
  }
}

// Get current environment
export function getEnvironment() {
  return NODE_ENV;
}
