// Merge curation batch JSONs into src/data/projects.json (+ home.json picks).
// Usage: node tools/merge-curation.js <dir-with-curation-*.json>
// Also emits <dir>/curation-flags.md — photo issues for human review.
const fs = require('fs');
const path = require('path');

const dir = process.argv[2];
if (!dir) { console.error('usage: node tools/merge-curation.js <dir>'); process.exit(1); }

const ROOT = path.join(__dirname, '..');
const projPath = path.join(ROOT, 'src', 'data', 'projects.json');
const homePath = path.join(ROOT, 'src', 'data', 'home.json');
const projects = JSON.parse(fs.readFileSync(projPath, 'utf8'));
const home = JSON.parse(fs.readFileSync(homePath, 'utf8'));
const bySlug = Object.fromEntries(projects.map(p => [p.slug, p]));

const flagsReport = [];
let applied = 0, homepageMap = null;

for (const f of fs.readdirSync(dir).filter(f => /^curation-.*\.json$/.test(f)).sort()) {
  const entries = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8'));
  for (const e of entries) {
    if (e.slug === '_homepage') { homepageMap = e; continue; }
    const p = bySlug[e.slug];
    if (!p) { console.error('unknown slug:', e.slug); continue; }
    if (Number.isInteger(e.heroIndex) && e.heroIndex >= 0 && e.heroIndex < p.images.length) p.heroIndex = e.heroIndex;
    if (Array.isArray(e.hiddenIndices)) p.hiddenIndices = e.hiddenIndices;
    if (e.blurb) p.blurb = e.blurb;
    if (e.heroAlt) p.heroAlt = e.heroAlt;
    if (e.tileLabel) p.tileLabel = e.tileLabel;
    if (Array.isArray(e.flags) && e.flags.length) flagsReport.push({ slug: e.slug, flags: e.flags });
    applied++;
  }
}

if (homepageMap && homepageMap.homepageMap) {
  const m = homepageMap.homepageMap;
  const set = (target, key) => {
    const hit = m[key];
    if (hit && bySlug[hit.slug] && Number.isInteger(hit.imageIndex)) {
      target.slug = hit.slug; target.index = hit.imageIndex;
    }
  };
  set(home.hero, 'thampi-2.jpg');
  const reelKeys = ['thampi-2.jpg', 'pamba-villa.jpg', 'orion.jpg', 'greendine-interior.jpg', 'bison-valley.jpg'];
  home.reel.forEach((r, i) => set(r, reelKeys[i]));
  const gridKeys = ['jayakumar-house.jpg', 'shanu-house.jpg', 'achayans-cafe.jpg', 'rajeev-house.jpg'];
  home.grid.forEach((g, i) => set(g, gridKeys[i]));
  set(home.studio, 'art-office.jpg');
  if (homepageMap.heroSourceWidth) console.log('hero source width:', homepageMap.heroSourceWidth, 'px');
}

fs.writeFileSync(projPath, JSON.stringify(projects, null, 2));
fs.writeFileSync(homePath, JSON.stringify(home, null, 2));
fs.writeFileSync(path.join(dir, 'curation-flags.md'),
  '# Photo issues flagged during curation\n\n' +
  flagsReport.map(r => `## ${r.slug}\n${r.flags.map(f => `- ${f}`).join('\n')}`).join('\n\n') + '\n');

const missingBlurbs = projects.filter(p => !p.blurb).map(p => p.slug);
console.log(`merged ${applied} entries; ${missingBlurbs.length} projects still without blurb${missingBlurbs.length ? ': ' + missingBlurbs.join(', ') : ''}`);
