// Patched pseudonymizer.js — v2 (fixes quote issue in regions string)
const abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
function nextLetter(i){ return abc[i] || ('X'+(i-abc.length+1)); }

export function pseudonymizeToMarkdown(input){
  const mapping = [];
  const map = new Map();
  let counters = { agent:1, poste:0, service:0, lieu:0, org:0, mail:0, ip:1 };

  function addMap(original, code, type){
    if(!original) return code;
    if(map.has(original)) return map.get(original);
    map.set(original, code);
    mapping.push({original, code, type});
    return code;
  }

  let text = input;

  // Emails
  text = text.replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, (m)=> addMap(m, `Mail ${nextLetter(counters.mail++)}`, 'email'));

  // IPv4
  text = text.replace(/\b(\d{1,3}\.){3}\d{1,3}\b/g, (m)=> addMap(m, 'IP-' + String(counters.ip++).padStart(3,'0'), 'ip'));

  // Acronyme + Région (quoted with double-quotes so d'Azur won't break)
  const regions = "(Grand\\s+Est|Nouvelle\\s+Aquitaine|Auvergne[-\\s]Rhône[-\\s]Alpes|Bourgogne[-\\s]Franche[-\\s]Comté|Bretagne|Centre[-\\s]Val[-\\s]de[-\\s]Loire|Corse|Guadeloupe|Guyane|Hauts[-\\s]de[-\\s]France|Île[-\\s]de[-\\s]France|La\\s+Réunion|Martinique|Mayotte|Normandie|Occitanie|Pays\\s+de\\s+la\\s+Loire|Provence[-\\s]Alpes[-\\s]Côte[-\\s]d'Azur)";
  const acr = "(?:[A-Z]{2,6}(?:-[A-Z]{2,6})*)";
  const acrPlusRegion = new RegExp(`\\b(${acr})\\s+(${regions})\\b`, 'gu');
  text = text.replace(acrPlusRegion, (m, a, r) => addMap(`${a} ${r}`, `ORG ${nextLetter(counters.org++)}`, 'org'));

  // Acronymes seuls
  const acrOnly = new RegExp(`\\b${acr}\\b`, 'gu');
  text = text.replace(acrOnly, (m)=> addMap(m, `ORG ${nextLetter(counters.org++)}`, 'org'));

  // Services — hyphen at end of class to avoid range
  const serviceRe = /\b(Service)\s+([A-ZÉÈÀÂÇÎÔÛ][\p{L}’' ]+[-]?[\p{L}’' ]*)/gu;
  text = text.replace(serviceRe, (s, kw, rest)=> addMap(`${kw} ${rest.trim()}`, `Service ${nextLetter(counters.service++)}`, 'service'));

  // Lieux — includes "Hôtel de Ville" variations
  const lieuHeads = [
    'Bâtiment','Batiment','Rue','Avenue','Bd','Boulevard','Place','Gare','Parc','Campus',
    'Préfecture','Prefecture','Hôtel\\s+de\\s+Ville','Hotel\\s+de\\s+Ville','Site','Bureau','Immeuble'
  ];
  const lieuRe = new RegExp(`\\b(?:${lieuHeads.join('|')})\\s+([A-ZÉÈÀÂÇÎÔÛ][\\p{L}’' ]+(?:-[\\p{L}’' ]+)*)`, 'gu');
  text = text.replace(lieuRe, (s)=> addMap(s, `Lieu ${nextLetter(counters.lieu++)}`, 'lieu'));

  // Fonctions
  const fonctions = ['Directeur','Directrice','Responsable','Cheffe? de projet','Chef de projet','Ingénieure?','Technicien(ne)?','Chargé(e)? de mission','Architecte','Analyste','Développeur(se)?','Administrateur(trice)?','Juriste'];
  const funcRe = new RegExp(`\\b(${fonctions.join('|')})(?:\\s+[A-ZÉÈÀÂÇÎÔÛ][\\p{L}\\-']+)*`, 'gu');
  text = text.replace(funcRe, (m)=> addMap(m, `Poste ${nextLetter(counters.poste++)}`, 'poste'));

  // Titres + Prénom Nom
  const titreRe = /(M\.?|Mme|Mlle|Monsieur|Madame)\s+([A-ZÉÈÀÂÇÎÔÛ][\p{L}\-']+)\s+([A-ZÉÈÀÂÇÎÔÛ][\p{L}\-']+)/gu;
  text = text.replace(titreRe, (s, t, p, n)=> addMap(`${t} ${p} ${n}`, `Agent ${counters.agent++}`, 'agent'));

  // Prénom Nom
  const prenomNom = /\b([A-ZÉÈÀÂÇÎÔÛ][\p{L}\-']+)\s+([A-ZÉÈÀÂÇÎÔÛ][\p{L}\-']+)\b/gu;
  text = text.replace(prenomNom, (s, p, n)=>{
    if (/^[A-Z]{2,}$/.test(p) || /^[A-Z]{2,}$/.test(n)) return s;
    if (map.has(s)) return map.get(s);
    return addMap(s, `Agent ${counters.agent++}`, 'agent');
  });

  const header = '| Donnée d’origine | Code anonymisé |\n|---|---|\n';
  const body = mapping.map(m => `| ${escapeMD(m.original)} | ${escapeMD(m.code)} |`).join('\n');
  const markdown = text + '\n\n' + header + body + '\n';
  return { markdown, mapping };
}

function escapeMD(s){ return String(s).replace(/\|/g,'\\|'); }
