/**
 * Commit many enemy south sprites from a JSON file (one manifest version bump).
 *
 * File format: [ { "slug": "golem_l8_10_forest", "objectId": "uuid" }, ... ]
 * slug = enemies.type without enemy. prefix or .south suffix
 *
 *   node scripts/pixellab-commit-enemy-south-pairs-file.mjs path/to/pairs.json
 */

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 file = process.argv[2];
  if (!file) {
    console.error('Usage: node scripts/pixellab-commit-enemy-south-pairs-file.mjs <pairs.json>');
    process.exit(1);
  }
  const pairs = JSON.parse(fs.readFileSync(file, 'utf8'));
  if (!Array.isArray(pairs) || pairs.length === 0) {
    console.error('Expected non-empty JSON array');
    process.exit(1);
  }
  if (pairs.length > 120) {
    console.error('Max 120 pairs per run');
    process.exit(1);
  }

  const manifest = JSON.parse(fs.readFileSync(MANIFEST, 'utf8'));
  for (const p of pairs) {
    const slug = p.slug;
    const objectId = p.objectId;
    if (!slug || !objectId) throw new Error('Each entry needs slug and objectId');
    const key = `enemy.${slug}.south`;
    const fileRel = `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', fileRel);
    await download(url, dest);
    entry.pixellabObjectId = objectId;
    entry.file = fileRel;
    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');
  console.log('Wrote manifest version', manifest.version, 'count', pairs.length);
}

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