import { LootTables } from "./loot-tables.js";
import { isOriginCell } from "./grid-utils.js";
import { getTotalAnimalValue } from "./income-value.js";
import { getOriginAnimalCount } from "./food.js";

/**
 * Attractivity from value, species count, rarity and fill rate (before penalties).
 * @param {import("./types.js").GameState} state
 * @returns {{ valueNorm: number, speciesNorm: number, rarityNorm: number, fillNorm: number }}
 */
export function getAttractivityBase(state) {
  const value = getTotalAnimalValue(state);
  const originCount = getOriginAnimalCount(state);
  const grid = state.grid;
  const cellCount = grid.width * grid.height;
  const fillRate = cellCount > 0 ? originCount / cellCount : 0;
  const speciesSet = new Set();
  let raritySum = 0;
  for (const [key, cell] of Object.entries(state.grid.cells)) {
    if (cell === null || cell === undefined || cell.kind !== "animal" || !isOriginCell(key, cell)) {
      // skip
    } else {
      speciesSet.add(cell.id);
      const def = LootTables.Animals[cell.id];
      if (def) raritySum += def.rarityLevel ?? 1;
    }
  }
  const speciesCount = speciesSet.size;
  const avgRarity = originCount > 0 ? raritySum / originCount : 0;
  return {
    valueNorm: value * 0.001,
    speciesNorm: speciesCount * 2,
    rarityNorm: avgRarity * 0.5,
    fillNorm: fillRate * 10,
  };
}
