import * as stat from "./planetStat.js";

const getRandomInt = (rng, min, max) => Math.floor(rng() * (max - min + 1)) + min;
const pick = (rng, array) => array[Math.floor(rng() * array.length)];

const randomPlanetTypeKey = (rng, planetType) => {
  const keys = Object.keys(planetType);
  return keys[Math.floor(rng() * keys.length)];
};

const distributePercentages = (rng, items) => {
  if (items.length === 0) return {};
  if (items.length === 1) return { [items[0]]: 100 };

  const cuts = Array.from({ length: items.length - 1 }, () => rng()).sort((a, b) => a - b);
  const segs = cuts.map((p, i) => (i === 0 ? p * 100 : (cuts[i] - cuts[i - 1]) * 100));
  segs.push((1 - cuts[items.length - 2]) * 100);
  return Object.fromEntries(items.map((item, idx) => [item, segs[idx]]));
};

export function buildPlanetTypeDistributions(rng) {
  for (const key in stat.planetType) {
    const type = stat.planetType[key];
    if (Array.isArray(type.elements)) type.distributedElements = distributePercentages(rng, type.elements);
    if (Array.isArray(type.resources)) type.distributedResources = distributePercentages(rng, type.resources);
  }
}

export function generatePlanet(rng) {
  // Distributions are normally created once at startup, but since we run per-cell with per-cell rng,
  // we generate per planet for stable, deterministic results from the same seed.
  buildPlanetTypeDistributions(rng);

  const planetTypeGeneration = randomPlanetTypeKey(rng, stat.planetType);
  const planetName = pick(rng, stat.planetNamePrefix) + pick(rng, stat.planetNameSuffix); // don't touch it
  const planetPopulationPeople = pick(rng, stat.planetType[planetTypeGeneration].populationType);
  const planetPopulationNumber =
    (stat.planetType[planetTypeGeneration].population * getRandomInt(rng, 50, 150)) / 99.9;

  return {
    name: planetName,
    type: planetTypeGeneration,
    population: {
      billions: Number(planetPopulationNumber.toFixed(3)),
      majority: planetPopulationPeople,
    },
    production: stat.planetType[planetTypeGeneration].distributedElements,
    naturalResources: stat.planetType[planetTypeGeneration].distributedResources,
  };
}

export function formatPlanet(planet) {
  const elementsDescription = Object.entries(planet.production)
    .map(([k, v]) => `    ${k}: ${v.toFixed(1)}%`)
    .join("\n");

  const resourcesDescription = Object.entries(planet.naturalResources)
    .map(([k, v]) => `    ${k}: ${v.toFixed(3)}%`)
    .join("\n");

  return `Planète : ${planet.name}

Type : ${planet.type}

Production :
${elementsDescription}

Ressources naturelles :
${resourcesDescription}

Population :

    ${planet.population.billions.toFixed(3)} milliards
    Majoritairement ${planet.population.majority}`;
}

