/**
 * §13 step 0's one remaining host probe, folded into Step 1.
 *
 * messagepal-backend proves the rest of the runtime baseline on this hosting, but
 * it does no image work — so `sharp` (native libvips) is unverified. Run this
 * locally now, and AGAIN on the cPanel host after the first deploy:
 *
 *     npm run check:sharp
 *
 * If the `sharp` import throws on the host, the fallback is the `@jsquash/*` WASM
 * codecs — a one-file swap in derivative.service.ts when step 5 builds it
 * (PLANNING.md §7). This script also reports whether ImageMagick is on PATH, the
 * third option named in §7.
 *
 * Exit code is non-zero on any failure so it can gate a deploy script.
 */
import { spawnSync } from 'node:child_process';

async function main(): Promise<void> {
  let failed = false;

  console.log(`platform: ${process.platform} ${process.arch}   node: ${process.version}\n`);

  // 1. Can sharp load at all?
  let sharp: typeof import('sharp');
  try {
    sharp = (await import('sharp')).default;
  } catch (err) {
    console.error(
      'FAIL  sharp failed to import — switch to the @jsquash/* WASM path (PLANNING.md §7).',
    );
    console.error(err);
    process.exit(1);
  }

  console.log('OK    sharp imported');
  console.log(`      versions: ${JSON.stringify(sharp.versions)}`);
  console.log(`      SIMD: ${sharp.simd()}   concurrency: ${sharp.concurrency()}\n`);

  // 2. Can it actually encode each format the media pipeline needs (§7)?
  const base = sharp({
    create: { width: 16, height: 16, channels: 3, background: { r: 120, g: 90, b: 60 } },
  });

  for (const format of ['avif', 'webp', 'jpeg'] as const) {
    try {
      const buf = await base.clone().toFormat(format).toBuffer();
      if (buf.length === 0) throw new Error('empty buffer');
      console.log(`OK    ${format.padEnd(4)} encode -> ${buf.length} bytes`);
    } catch (err) {
      failed = true;
      console.error(`FAIL  ${format} encode:`, err instanceof Error ? err.message : err);
    }
  }

  // 3. Is ImageMagick available as a shell-out fallback? (informational)
  console.log('');
  for (const bin of ['magick', 'convert']) {
    const probe = spawnSync(bin, ['-version'], { encoding: 'utf8' });
    if (probe.status === 0) {
      console.log(`OK    ImageMagick present via \`${bin}\`: ${probe.stdout.split('\n')[0]}`);
    } else {
      console.log(`--    \`${bin}\` not on PATH`);
    }
  }

  console.log('');
  if (failed) {
    console.error('check-sharp: FAILED — see above.');
    process.exit(1);
  }
  console.log('check-sharp: OK — sharp is usable on this host.');
}

void main();
