// Generate REAL embeddable SymView + FpView HTML via the adom-symbol / adom-footprint
// app generators, for each chip, into /tmp/nrf-site/<slug>/{symview,fpview}.html.
import { generateBrandedViewer } from '/home/adom/project/gallia/symbol-creator/lib/viewer-gen.js';
import { generateFootprintViewer } from '/tmp/gen/fpv/kicad-footprint-viewer.js';
import { readFileSync, writeFileSync, existsSync } from 'fs';
import { execSync } from 'child_process';

const LIB='/home/adom/project/chip-fetcher/library';
const OUT='/tmp/nrf-site';
const CHIPS=[
 ['nRF54L15','nrf54l15','Nordic Semiconductor'],
 ['DMG2305UX-7','dmg2305','Diodes Incorporated'],
 ['LM358D','lm358d','Texas Instruments'],
 ['BME688','bme688','Bosch Sensortec'],
 ['TPS25751SRSMR','tps25751','Texas Instruments'],
 ['WSL2010R0500FEA','wsl2010','Vishay'],
];
function g(d,p){try{return execSync(`ls ${d}/${p} 2>/dev/null|head -1`).toString().trim()}catch(e){return ''}}
for(const [mpn,slug,mfr] of CHIPS){
  const D=`${LIB}/${mpn}`;
  // pin descriptions from ds2sf
  let pinDescriptions={},groupDescriptions={};
  const symx=g(D,`${mpn}-symbol.extracted.json`);
  if(symx){const s=JSON.parse(readFileSync(symx,'utf-8'));for(const p of (s.pins||[])){if(p.number)pinDescriptions[p.number]=p.description||'';}}
  // SymView via adom-symbol generator (pre-rendered SVG -> no service-kicad needed)
  const symSvgP=g(D,`${mpn}-symbol.svg`), symP=g(D,`${mpn}.kicad_sym`);
  try{
    const html=await generateBrandedViewer(symP,mpn,{svgContent:readFileSync(symSvgP,'utf-8'),pinDescriptions,manufacturer:mfr});
    writeFileSync(`${OUT}/${slug}/symview.html`,html); console.log(`${slug} symview: ${html.length} bytes`);
  }catch(e){console.log(`${slug} symview FAIL: ${e.message}`);}
  // FpView via adom-footprint generator (shim feeds the real rendered footprint SVG)
  const fpSvgP=g(D,`${mpn}-footprint.svg`), modP=g(D,`${mpn}.kicad_mod`);
  try{
    process.env.FP_SVG = fpSvgP||'';
    const html=await generateFootprintViewer(modP,mpn,{manufacturer:mfr,partName:mpn});
    writeFileSync(`${OUT}/${slug}/fpview.html`,html); console.log(`${slug} fpview: ${html.length} bytes`);
  }catch(e){console.log(`${slug} fpview FAIL: ${e.message}`);}
}