#!/usr/bin/env node
/**
 * gen-footprint-viewer.mjs — generate <MPN>-footprint-viewer.html (FpView)
 * for one chip. Mirrors gen-symbol-viewer.mjs's pattern:
 *   1. Pre-render the .kicad_mod → SVG via local kicad-cli (using a shim
 *      .pretty/ dir, since kicad-cli demands one for fp export).
 *   2. Pass that SVG content directly to gallia's generateFootprintViewer
 *      via the new svgContent option, bypassing the broken HTTP route.
 *   3. Write <MPN>-footprint-viewer.html into the chip's library dir.
 *
 * Usage:
 *   node gen-footprint-viewer.mjs <library-dir>/<MPN>
 */

import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync, copyFileSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { execFileSync } from 'child_process';
import { join, basename, resolve } from 'path';

const arg = process.argv[2];
if (!arg) {
  console.error('usage: gen-footprint-viewer.mjs <library-dir>/<MPN>');
  process.exit(2);
}

const dir = resolve(arg);
const mpn = basename(dir);
const fpPath = join(dir, `${mpn}.kicad_mod`);
if (!existsSync(fpPath)) {
  console.error(`ERROR: ${fpPath} not found`);
  process.exit(1);
}

// ── kicad-cli fp export svg requires a .pretty/ dir input ──
const tmp = mkdtempSync(join(tmpdir(), 'cf-fpview-'));
const pretty = join(tmp, `${mpn}.pretty`);
mkdirSync(pretty, { recursive: true });
copyFileSync(fpPath, join(pretty, `${mpn}.kicad_mod`));

try {
  execFileSync('kicad-cli', [
    'fp', 'export', 'svg',
    '--layers', 'F.Cu,F.SilkS,F.Mask,F.Fab,Edge.Cuts',
    '--output', tmp,
    pretty,
  ], { stdio: 'pipe' });
} catch (e) {
  console.error('ERROR: kicad-cli fp export svg failed:', e.stderr?.toString() || e.message);
  rmSync(tmp, { recursive: true, force: true });
  process.exit(1);
}

const svgFile = readdirSync(tmp).find(f => f.endsWith('.svg'));
if (!svgFile) {
  console.error('ERROR: kicad-cli produced no svg in', tmp);
  rmSync(tmp, { recursive: true, force: true });
  process.exit(1);
}
const svgContent = readFileSync(join(tmp, svgFile), 'utf-8');
rmSync(tmp, { recursive: true, force: true });

// ── Build FpView HTML via gallia's generateFootprintViewer ──
const { generateFootprintViewer } = await import(
  '/home/adom/project/gallia/viewer/kicad-footprint-viewer.js'
);

const infoPath = join(dir, 'info.json');
let info = {};
if (existsSync(infoPath)) {
  try { info = JSON.parse(readFileSync(infoPath, 'utf-8')); } catch {}
}

const html = await generateFootprintViewer(fpPath, mpn, {
  padDescriptions: {},
  symbolPinMap: {},
  datasheetUrl: info.datasheet_url && info.datasheet_url !== '?' ? info.datasheet_url : '',
  manufacturer: info.manufacturer && info.manufacturer !== '?' ? info.manufacturer : '',
  partName: mpn,
  svgContent,
});

const outPath = join(dir, `${mpn}-footprint-viewer.html`);
writeFileSync(outPath, html);
console.log(`OK: ${outPath} (${html.length} bytes)`);