/**
 * Sceau dynamique : SVG déterministe dont le guillochage est une trame tissée
 * dérivée des octets de l'empreinte SHA-256 de l'acte.
 */
import { IVOIRE, OR_POIDS, VERT_BANCO } from './couleurs.ts';
import { cosinus, DEUX_PI, nombre, sinus } from './determinisme.ts';
import { octetsDepuisEmpreinte } from './empreinte.ts';
import { parametresSceau, type ParametresSceau } from './motif.ts';

const TAILLE = 240;
const CENTRE = TAILLE / 2;
const RAYON_TRAME = 60;
const POINTS_PAR_FIL = 240;

export interface OptionsSceau {
  /**
   * Texte alternatif, déjà traduit (par exemple « Sceau de l'attestation … »).
   * Sans titre, le sceau est décoratif et masqué aux lecteurs d'écran.
   */
  titre?: string;
  /** Affiche l'empreinte en couronne (par défaut : oui). */
  afficherEmpreinte?: boolean;
  /** Préfixe des identifiants internes, si plusieurs sceaux identiques figurent sur une page. */
  prefixeId?: string;
}

const point = (rayon: number, angle: number) =>
  `${nombre(CENTRE + rayon * cosinus(angle))},${nombre(CENTRE + rayon * sinus(angle))}`;

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

/** Fils de chaîne (sens direct, vert) et de trame (sens inverse, or) qui se croisent. */
function trame(p: ParametresSceau): string {
  const fils: string[] = [];
  for (let i = 0; i < p.fils; i += 1) {
    const chaine = i % 2 === 0;
    const sens = chaine ? 1 : -1;
    // Phases réparties sur une période complète : les fils se croisent comme une trame tissée.
    const phase = (i * DEUX_PI) / p.fils + (chaine ? 0 : p.decalage * DEUX_PI);
    const points: string[] = [];
    for (let j = 0; j < POINTS_PAR_FIL; j += 1) {
      const theta = (j * DEUX_PI) / POINTS_PAR_FIL;
      const rayon =
        RAYON_TRAME +
        p.amplitude * sinus(sens * p.petales * theta + phase) +
        p.amplitudeSecondaire * sinus(2 * p.petales * theta - 2 * phase);
      points.push(point(rayon, theta));
    }
    const couleur = chaine ? VERT_BANCO : OR_POIDS;
    fils.push(
      `<polygon points="${points.join(' ')}" fill="none" stroke="${couleur}" stroke-width="0.9"/>`,
    );
  }
  return fils.join('');
}

/** Couronne de poids akan : carrés et losanges alternés selon les bits de l'empreinte. */
function poidsAkan(p: ParametresSceau): string {
  const cote = 4.4;
  return p.formesGlyphes
    .map((carre, i) => {
      const angle = (i * DEUX_PI) / p.glyphes;
      const degres = (i * 360) / p.glyphes + (carre ? 0 : 45);
      const [x, y] = point(32, angle).split(',');
      return `<rect x="${nombre(-cote / 2)}" y="${nombre(-cote / 2)}" width="${cote}" height="${cote}" transform="translate(${x ?? '0'} ${y ?? '0'}) rotate(${nombre(degres)})" fill="${carre ? VERT_BANCO : OR_POIDS}"/>`;
    })
    .join('');
}

/** Médaillon central : carrés ou losanges imbriqués, ou spirale. */
function medaillon(p: ParametresSceau): string {
  if (p.central === 'spirale') {
    const tours = p.niveaux;
    const pas = 18 / (tours * DEUX_PI);
    const nbPoints = 48 * tours;
    const points: string[] = [];
    for (let j = 0; j <= nbPoints; j += 1) {
      const theta = (j * tours * DEUX_PI) / nbPoints;
      points.push(point(2 + pas * theta, theta));
    }
    return `<polyline points="${points.join(' ')}" fill="none" stroke="${VERT_BANCO}" stroke-width="1.6" stroke-linecap="round"/><circle cx="${CENTRE}" cy="${CENTRE}" r="1.8" fill="${OR_POIDS}"/>`;
  }
  const formes: string[] = [];
  for (let n = 0; n < p.niveaux; n += 1) {
    const cote = 30 - n * (24 / p.niveaux);
    const rotation = p.central === 'losange' ? 45 : 0;
    formes.push(
      `<rect x="${nombre(CENTRE - cote / 2)}" y="${nombre(CENTRE - cote / 2)}" width="${nombre(cote)}" height="${nombre(cote)}" transform="rotate(${rotation} ${CENTRE} ${CENTRE})" fill="none" stroke="${n % 2 === 0 ? VERT_BANCO : OR_POIDS}" stroke-width="1.6"/>`,
    );
  }
  return formes.join('');
}

/** Paramètres visuels associés à une empreinte (utile pour les tests et l'explication du sceau). */
export function parametresDuSceau(empreinteHex: string): ParametresSceau {
  return parametresSceau(octetsDepuisEmpreinte(empreinteHex));
}

/**
 * Renvoie le SVG déterministe du sceau associé à une empreinte SHA-256 :
 * même empreinte, même SVG, au caractère près, sur toutes les plateformes.
 */
export function genererSceau(empreinteHex: string, options: OptionsSceau = {}): string {
  const p = parametresSceau(octetsDepuisEmpreinte(empreinteHex));
  const id = options.prefixeId ?? `nci-sceau-${empreinteHex.slice(0, 12)}`;
  const afficherEmpreinte = options.afficherEmpreinte ?? true;

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

  const couronne = afficherEmpreinte
    ? `<path id="${id}-anneau" d="M ${CENTRE} ${CENTRE - 103} a 103 103 0 1 1 0 206 a 103 103 0 1 1 0 -206" fill="none"/>` +
      `<text font-family="'JetBrains Mono Variable', ui-monospace, monospace" font-size="7.4" fill="${VERT_BANCO}">` +
      `<textPath href="#${id}-anneau" textLength="640" lengthAdjust="spacing">${empreinteHex}</textPath></text>`
    : '';

  return (
    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${TAILLE} ${TAILLE}" ${accessibilite}` +
    `<circle cx="${CENTRE}" cy="${CENTRE}" r="116" fill="${IVOIRE}" stroke="${VERT_BANCO}" stroke-width="3"/>` +
    `<circle cx="${CENTRE}" cy="${CENTRE}" r="111" fill="none" stroke="${OR_POIDS}" stroke-width="1"/>` +
    couronne +
    `<circle cx="${CENTRE}" cy="${CENTRE}" r="93" fill="none" stroke="${VERT_BANCO}" stroke-width="1.2"/>` +
    `<g transform="rotate(${p.rotation} ${CENTRE} ${CENTRE})">` +
    trame(p) +
    poidsAkan(p) +
    medaillon(p) +
    `</g></svg>`
  );
}
