import { getConfig } from "./configLoader.js";
import {
  ensureSeedEpoch,
  getGridCells,
  addEconScore,
  setElementBonus,
} from "./db/gameDb.js";
import { computeTeamIncome, computeTeamElementBonus } from "./helpers/economy.js";

const TICK_SECONDS = 5;

/**
 * Starts the server-side economy tick loop.
 * Runs every TICK_SECONDS, reads the current grid from the DB, computes
 * income and element bonus for each team, and persists the results.
 * This runs independently of any connected browser.
 */
export function startEconTick() {
  setInterval(async () => {
    try {
      const worldSeed = await ensureSeedEpoch();
      const rows = await getGridCells(worldSeed);
      const cfg = getConfig();

      const resourceWorth = cfg.resourceWorth ?? { common: {}, rare: {} };
      const elementWorth  = cfg.elementWorth  ?? {};

      // ── Economic score deltas ─────────────────────────────────────────────
      const blueIncome = computeTeamIncome("blue", rows, resourceWorth);
      const redIncome  = computeTeamIncome("red",  rows, resourceWorth);

      const blueDelta = blueIncome * TICK_SECONDS;
      const redDelta  = redIncome  * TICK_SECONDS;

      if (blueDelta > 0) await addEconScore(worldSeed, "blue", blueDelta);
      if (redDelta  > 0) await addEconScore(worldSeed, "red",  redDelta);

      // ── Element bonus (overwrites; reflects current grid state) ──────────
      const blueBonus = computeTeamElementBonus("blue", rows, elementWorth);
      const redBonus  = computeTeamElementBonus("red",  rows, elementWorth);

      await setElementBonus(worldSeed, "blue", blueBonus);
      await setElementBonus(worldSeed, "red",  redBonus);
    } catch (e) {
      console.error("[econ tick]", e.message);
    }
  }, TICK_SECONDS * 1_000);
}
