// Pipeline asset: extract-fig-images.sh → apply-asset-map.mjs → optimize-assets.sh → extract-logos.sh
// 1. extract-fig-images.sh: estrae hash-named images da .fig → assets-src/
// 2. apply-asset-map.mjs:   copia da assets-src/ → destinazioni (src/assets/img, public/img)
// 3. optimize-assets.sh:    converte PNG fotografici → JPG q85, ridimensiona ≤1400px
// 4. extract-logos.sh:      estrae loghi insanitylab da FigmaDoc/Homepage.pdf → public/img/logo-{dark,light}.png

import { copyFileSync, mkdirSync, existsSync } from 'node:fs';
import { readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const root = join(dirname(fileURLToPath(import.meta.url)), '..');
const map = JSON.parse(readFileSync(join(root, 'scripts/asset-map.json'), 'utf8'));
let n = 0, missing = 0;

// Sezione principale: copia da assets-src/
for (const [destDir, entries] of Object.entries(map)) {
  if (destDir.startsWith('_') || destDir === 'fallbacks') continue;
  mkdirSync(join(root, destDir), { recursive: true });
  for (const [src, dest] of Object.entries(entries)) {
    const from = join(root, 'assets-src', src);
    if (!existsSync(from)) { console.error(`MANCANTE: ${src}`); missing++; continue; }
    copyFileSync(from, join(root, destDir, dest));
    n++;
  }
}

// Sezione fallbacks: copia da path relativo alla root del repo (es. ../Dati/)
if (map.fallbacks) {
  for (const [destDir, entries] of Object.entries(map.fallbacks)) {
    mkdirSync(join(root, destDir), { recursive: true });
    for (const [srcRelPath, dest] of Object.entries(entries)) {
      const from = join(root, srcRelPath);
      if (!existsSync(from)) { console.error(`MANCANTE (fallback): ${srcRelPath}`); missing++; continue; }
      copyFileSync(from, join(root, destDir, dest));
      n++;
    }
  }
}

console.log(`Copiate ${n} immagini${missing ? `, ${missing} mancanti` : ''}`);
process.exit(missing ? 1 : 0);
