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 {{ dailyActionQuota: number, teamActionQuota: number, databaseWipeoutIntervalSeconds: number, configReloadIntervalSeconds: number, resourceWorth: object, militaryPower: object }} */
let cached = {
  dailyActionQuota: 100,
  teamActionQuota: 100,
  databaseWipeoutIntervalSeconds: 21600,
  configReloadIntervalSeconds: 30,
  elementWorth: {},
  resourceWorth: { common: {}, rare: {} },
  militaryPower: {},
};

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.dailyActionQuota === "number" && j.dailyActionQuota >= 1) {
      cached.dailyActionQuota = Math.floor(j.dailyActionQuota);
    }
    if (typeof j.teamActionQuota === "number" && j.teamActionQuota >= 1) {
      cached.teamActionQuota = Math.floor(j.teamActionQuota);
    }
    if (typeof j.databaseWipeoutIntervalSeconds === "number" && j.databaseWipeoutIntervalSeconds >= 60) {
      cached.databaseWipeoutIntervalSeconds = j.databaseWipeoutIntervalSeconds;
    }
    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;
    }    if (j.militaryPower && typeof j.militaryPower === 'object') {
      cached.militaryPower = j.militaryPower;
    }    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;
}
