const fs = require('fs');
const path = require('path');
const dir = path.join(__dirname, 'project/floors');
const files = fs.readdirSync(dir).filter(f => f.startsWith('MT') && f.endsWith('.js'));
const colors = ['red', 'blue', 'yellow'];
const entries = [];

function walk(obj, floorId, ctx) {
  if (!obj || typeof obj !== 'object') return;
  if (Array.isArray(obj)) {
    obj.forEach(item => walk(item, floorId, ctx));
    return;
  }
  if (obj.type === 'setBlock' && colors.includes(obj.number)) {
    let locs = obj.loc;
    const ev = ctx.eventXY;
    if (!locs && ev) locs = [[ev[0], ev[1]]];
    else if (locs && typeof locs[0] === 'number') locs = [locs];
    if (!locs) {
      entries.push({ floor: floorId, color: obj.number, x: null, y: null, path: ctx.path, note: 'NO_LOC' });
      return;
    }
    for (const loc of locs) {
      entries.push({ floor: floorId, color: obj.number, x: loc[0], y: loc[1], path: ctx.path });
    }
  }
  for (const k of Object.keys(obj)) {
    if (k === 'events' && typeof obj[k] === 'object') {
      for (const ek of Object.keys(obj[k])) {
        const [ex, ey] = ek.split(',').map(Number);
        const val = obj[k][ek];
        if (Array.isArray(val)) walk(val, floorId, { path: 'events/' + ek, eventXY: [ex, ey] });
        else if (val && val.data) walk(val.data, floorId, { path: 'events/' + ek, eventXY: [ex, ey] });
        else walk(val, floorId, { path: 'events/' + ek, eventXY: [ex, ey] });
      }
    } else if (['afterBattle', 'afterGetItem', 'afterOpenDoor', 'beforeBattle', 'autoEvent'].includes(k)) {
      const ab = obj[k];
      if (typeof ab === 'object') {
        for (const ek of Object.keys(ab)) {
          if (ek === '0' || ek === '1') continue; // autoEvent nested
          const val = ab[ek];
          if (k === 'autoEvent' && typeof val === 'object' && !Array.isArray(val)) {
            for (const sub of Object.keys(val)) {
              if (sub === 'condition' || sub === 'currentFloor' || sub === 'priority') continue;
              walk(val[sub], floorId, { path: k + '/' + ek + '/' + sub, eventXY: null });
            }
          } else {
            walk(val, floorId, { path: k + '/' + ek, eventXY: ek.includes(',') ? ek.split(',').map(Number) : null });
          }
        }
      }
    } else if (k === 'floorId') floorId = obj.floorId;
    else walk(obj[k], floorId, ctx);
  }
}

for (const f of files) {
  const code = fs.readFileSync(path.join(dir, f), 'utf8');
  const m = code.match(/main\.floors\.\w+\s*=\s*(\{[\s\S]*\})\s*;?\s*$/);
  if (!m) continue;
  const floor = eval('(' + m[1] + ')');
  walk(floor, floor.floorId, { path: f });
}

entries.sort((a, b) => (a.floor + a.y + a.x).localeCompare(b.floor + b.y + b.x));
console.log(JSON.stringify(entries, null, 2));
console.error('count', entries.length);
