/**
 * After PixelLab MCP returns object IDs, save PNGs and set manifest pixellabObjectId.
 *
 * Usage (pairs: slug without enemy. prefix):
 *   node scripts/pixellab-commit-enemy-south-batch.mjs boar_l5_5_canyon <uuid> boar_l5_5_swamp <uuid> ...
 */

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.join(__dirname, '..');
const MANIFEST = path.join(ROOT, 'frontend/public/assets/game/manifest.json');

async function download(url, dest) {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`GET ${url} ${res.status}`);
  fs.mkdirSync(path.dirname(dest), { recursive: true });
  fs.writeFileSync(dest, Buffer.from(await res.arrayBuffer()));
}

async function main() {
  const args = process.argv.slice(2);
  if (args.length < 2 || args.length % 2 !== 0) {
    console.error('Need even number of args: slug objectId ...');
    process.exit(1);
  }
  const manifest = JSON.parse(fs.readFileSync(MANIFEST, 'utf8'));
  for (let i = 0; i < args.length; i += 2) {
    const slug = args[i];
    const objectId = args[i + 1];
    const key = `enemy.${slug}.south`;
    const file = `enemies/enemy.${slug}.south.png`;
    const entry = manifest.textures[key];
    if (!entry) throw new Error(`No manifest key ${key}`);
    const url = `https://api.pixellab.ai/mcp/map-objects/${objectId}/download`;
    const dest = path.join(ROOT, 'frontend/assets', file);
    await download(url, dest);
    entry.pixellabObjectId = objectId;
    entry.file = file;
    entry.kind = 'map_object';
    entry.rotation = 'south';
    console.log('OK', key);
  }
  manifest.version = (manifest.version ?? 0) + 1;
  fs.writeFileSync(MANIFEST, JSON.stringify(manifest, null, 2) + '\n', 'utf8');
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
});
