import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const CONFIG_FILE_PATH =
  process.env.CONFIG_FILE_PATH ?? path.join(__dirname, "..", "config", "game.settings.json");

/** @type {{ clickCooldownSeconds: number, databaseWipeoutIntervalSeconds: number, debugModeForTeams: boolean, configReloadIntervalSeconds: number, resourceWorth: object }} */
let cached = {
  clickCooldownSeconds: 5,
  databaseWipeoutIntervalSeconds: 21600,
  debugModeForTeams: true,
  configReloadIntervalSeconds: 30,
  elementWorth: {},
  resourceWorth: { common: {}, rare: {} },
};

let lastMtimeMs = 0;

function parseBool(v) {
  if (typeof v === "boolean") return v;
  if (typeof v === "string") {
    const s = v.trim().toLowerCase();
    if (s === "true") return true;
    if (s === "false") return false;
  }
  return null;
}

export function loadConfigFile() {
  try {
    const st = fs.statSync(CONFIG_FILE_PATH);
    if (st.mtimeMs === lastMtimeMs) {
      return cached;
    }
    const raw = fs.readFileSync(CONFIG_FILE_PATH, "utf8");
    const j = JSON.parse(raw);
    if (typeof j.clickCooldownSeconds === "number" && j.clickCooldownSeconds >= 0) {
      cached.clickCooldownSeconds = j.clickCooldownSeconds;
    }
    if (typeof j.databaseWipeoutIntervalSeconds === "number" && j.databaseWipeoutIntervalSeconds >= 60) {
      cached.databaseWipeoutIntervalSeconds = j.databaseWipeoutIntervalSeconds;
    }
    const dbg = parseBool(j.debugModeForTeams);
    if (dbg !== null) cached.debugModeForTeams = dbg;
    if (typeof j.configReloadIntervalSeconds === "number" && j.configReloadIntervalSeconds >= 5) {
      cached.configReloadIntervalSeconds = j.configReloadIntervalSeconds;
    }
    if (j.elementWorth && typeof j.elementWorth === "object") {
      cached.elementWorth = j.elementWorth;
    }
    if (j.resourceWorth && typeof j.resourceWorth === "object") {
      cached.resourceWorth = j.resourceWorth;
    }
    lastMtimeMs = st.mtimeMs;
  } catch (e) {
    if (e.code === "ENOENT") {
      lastMtimeMs = 0;
    } else {
      console.error("[config]", e.message);
    }
  }
  return cached;
}

export function getConfig() {
  return { ...cached };
}

export function getConfigFilePath() {
  return CONFIG_FILE_PATH;
}
