const fs = require('fs');
const path = require('path');

const LEGEND_PATH = path.join(__dirname, '..', 'public', 'overlay', 'gift-legend.json');
const PRICES_PATH = path.join(__dirname, '..', 'public', 'overlay', 'gift-prices.json');
const DIACRITICS_RE = new RegExp('[\\u0300-\\u036f]', 'g');

function normalizeKey(s) {
  return (s || '')
    .toString()
    .normalize('NFD')
    .replace(DIACRITICS_RE, '')
    .toLowerCase()
    .replace(/[^a-z0-9]/g, '');
}

/**
 * Charge gift-legend.json (+ gift-prices.json qui surcharge le prix de chaque
 * don, plus simple a corriger sans toucher au reste) et retourne la liste a
 * plat de tous les dons (grid + sideLeft + sideRight + special), plus un Set
 * de cles normalisees (id et nom) pour detecter rapidement un don connu/inconnu.
 */
function loadGiftLegend() {
  const raw = JSON.parse(fs.readFileSync(LEGEND_PATH, 'utf-8'));
  const flat = [...raw.grid, ...raw.sideLeft, ...raw.sideRight, raw.special];

  let prices = {};
  try {
    prices = JSON.parse(fs.readFileSync(PRICES_PATH, 'utf-8'));
  } catch (e) {
    // pas de fichier de prix : on garde les valeurs de gift-legend.json
  }

  const knownKeys = new Set();
  for (const entry of flat) {
    if (prices[entry.id] !== undefined) entry.diamonds = prices[entry.id];
    knownKeys.add(normalizeKey(entry.id));
    knownKeys.add(normalizeKey(entry.name));
    for (const a of entry.alias || []) knownKeys.add(normalizeKey(a));
  }

  return { flat, knownKeys, normalizeKey };
}

module.exports = { loadGiftLegend, normalizeKey };
