/**
 * QR code en SVG (navigateur, Deno, Node) et rastérisation en pixels (pour l'export PNG côté Node).
 * L'encodage QR est confié à `uqr` (ESM, sans dépendance) ; le rendu est le nôtre,
 * aux couleurs de la charte.
 */
import { encode } from 'uqr';
import { IVOIRE, VERT_BANCO } from './couleurs.ts';

export type NiveauCorrection = 'L' | 'M' | 'Q' | 'H';

export interface OptionsQR {
  /** Correction d'erreur (par défaut « M », environ 15 % du code peut être abîmé). */
  correction?: NiveauCorrection;
  /** Zone de silence autour du code, en modules (4 selon la norme ISO/IEC 18004). */
  marge?: number;
  couleur?: string;
  fond?: string;
  /** Texte alternatif déjà traduit. Sans titre, le QR est masqué aux lecteurs d'écran. */
  titre?: string;
}

/** Longueur maximale acceptée : une URL de vérification est courte. */
export const LONGUEUR_MAX_QR = 512;

/** Matrice du QR, sans marge : vrai = module foncé. */
export function matriceQR(contenu: string, correction: NiveauCorrection = 'M'): boolean[][] {
  if (contenu.length === 0) throw new TypeError('Le contenu du QR code est vide.');
  if (contenu.length > LONGUEUR_MAX_QR) {
    throw new RangeError(
      `Contenu trop long pour un QR code lisible (> ${LONGUEUR_MAX_QR} caractères).`,
    );
  }
  return encode(contenu, { ecc: correction, border: 0 }).data;
}

function echapper(texte: string): string {
  return texte
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

/** QR code en SVG. Les modules contigus d'une ligne sont fusionnés pour alléger le fichier. */
export function genererQR(url: string, options: OptionsQR = {}): string {
  const matrice = matriceQR(url, options.correction);
  const marge = options.marge ?? 4;
  const taille = matrice.length + 2 * marge;
  const traits: string[] = [];

  matrice.forEach((ligne, y) => {
    let x = 0;
    while (x < ligne.length) {
      if (!ligne[x]) {
        x += 1;
        continue;
      }
      const debut = x;
      while (x < ligne.length && ligne[x]) x += 1;
      traits.push(`M${debut + marge} ${y + marge}h${x - debut}v1h-${x - debut}z`);
    }
  });

  const accessibilite = options.titre
    ? `role="img"><title>${echapper(options.titre)}</title>`
    : 'aria-hidden="true">';

  return (
    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${taille} ${taille}" shape-rendering="crispEdges" ${accessibilite}` +
    `<rect width="${taille}" height="${taille}" fill="${options.fond ?? IVOIRE}"/>` +
    `<path d="${traits.join('')}" fill="${options.couleur ?? VERT_BANCO}"/></svg>`
  );
}

export interface ImageRGBA {
  largeur: number;
  hauteur: number;
  /** Pixels RGBA, ligne par ligne. */
  pixels: Uint8ClampedArray;
}

function couleurRGB(hex: string): [number, number, number] {
  const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex);
  if (!m) throw new TypeError(`Couleur hexadécimale invalide : ${hex}`);
  return [parseInt(m[1] ?? '0', 16), parseInt(m[2] ?? '0', 16), parseInt(m[3] ?? '0', 16)];
}

/** Rastérise le QR : `echelle` pixels par module. */
export function rasteriserQR(url: string, echelle = 8, options: OptionsQR = {}): ImageRGBA {
  if (!Number.isInteger(echelle) || echelle < 1)
    throw new RangeError('Échelle entière ≥ 1 attendue.');
  const matrice = matriceQR(url, options.correction);
  const marge = options.marge ?? 4;
  const modules = matrice.length + 2 * marge;
  const cote = modules * echelle;
  const [fr, fg, fb] = couleurRGB(options.couleur ?? VERT_BANCO);
  const [br, bg, bb] = couleurRGB(options.fond ?? IVOIRE);
  const pixels = new Uint8ClampedArray(cote * cote * 4);

  for (let py = 0; py < cote; py += 1) {
    const my = Math.floor(py / echelle) - marge;
    for (let px = 0; px < cote; px += 1) {
      const mx = Math.floor(px / echelle) - marge;
      const fonce = matrice[my]?.[mx] === true;
      const i = (py * cote + px) * 4;
      pixels[i] = fonce ? fr : br;
      pixels[i + 1] = fonce ? fg : bg;
      pixels[i + 2] = fonce ? fb : bb;
      pixels[i + 3] = 255;
    }
  }
  return { largeur: cote, hauteur: cote, pixels };
}
