#!/usr/bin/env node
'use strict';

const fs = require('fs');
const path = require('path');
const { pipeline } = require('stream/promises');

async function copyFileStream(src, dest) {
  await fs.promises.mkdir(path.dirname(dest), { recursive: true });
  await pipeline(fs.createReadStream(src), fs.createWriteStream(dest));
}

async function main() {
  const [srcDir, destDir] = process.argv.slice(2);
  if (!srcDir || !destDir) {
    console.error('usage: sync-images.js <srcDir> <destDir>');
    process.exit(2);
  }
  if (!fs.existsSync(srcDir)) {
    console.log(`  Images: source missing (${srcDir}), skipped`);
    return;
  }

  await fs.promises.rm(destDir, { recursive: true, force: true });
  await fs.promises.mkdir(destDir, { recursive: true });

  const entries = await fs.promises.readdir(srcDir, { withFileTypes: true });
  let copied = 0;
  let skipped = 0;
  for (const entry of entries) {
    if (!entry.isFile()) continue;
    const src = path.join(srcDir, entry.name);
    const dest = path.join(destDir, entry.name);
    try {
      await copyFileStream(src, dest);
      const stat = await fs.promises.stat(dest);
      if (stat.size === 0) throw new Error('copied zero-byte file');
      copied += 1;
    } catch (err) {
      skipped += 1;
      try { await fs.promises.unlink(dest); } catch {}
      if (skipped <= 5) {
        console.warn(`  Images: skipped ${entry.name}: ${err.message}`);
      }
    }
  }
  const suffix = skipped > 5 ? ` (${skipped - 5} more skipped)` : '';
  console.log(`  Images: synced ${copied}, skipped ${skipped}${suffix}`);
}

main().catch((err) => {
  console.error(`  Images: warning - image sync failed: ${err.message}`);
});
