#!/usr/bin/env node
const fs = require('fs');
const path = require('path');

function loadAsCJS(filepath, depExports = {}) {
  let src = fs.readFileSync(filepath, 'utf8');
  src = src.replace(/^'use babel';\s*$/gm, '');
  src = src.replace(/^import\s+\{([^}]+)\}\s+from\s+['"][^'"]+['"];?/gm,
    (_, names) => names.split(',').map(n => `const ${n.trim()} = __DEPS__.${n.trim()};`).join('\n')
  );
  const exportNames = [];
  src = src.replace(/^export\s+function\s+(\w+)/gm, (_, n) => { exportNames.push(n); return `function ${n}`; });
  src = src.replace(/^export\s+const\s+(\w+)/gm,    (_, n) => { exportNames.push(n); return `const ${n}`; });
  const wrapper = `(function(__DEPS__){\n${src}\nreturn { ${exportNames.join(', ')} };\n})`;
  return eval(wrapper)(depExports);
}

const libdir = path.join(__dirname, '..', 'lib');
const lcxl = loadAsCJS(path.join(libdir, 'lcxl-map.js'));
const kw   = loadAsCJS(path.join(libdir, 'tidal-keywords.js'));
const parser = loadAsCJS(path.join(libdir, 'parser.js'), { ...lcxl, ...kw });

const file = '/home/pln/Work/Sound/Tidal/live/midi/nova/ambient/quand_on_decolle.tidal';
const text = fs.readFileSync(file, 'utf8');
const result = parser.parse(text);

console.log(`orbits=${result.orbits.length} groups=${Object.keys(result.groups).length} errors=${result.errors.length}`);
if (result.errors.length) console.log('errors:', result.errors);
console.log('\nGROUPS:');
for (const [n, g] of Object.entries(result.groups)) {
  console.log(`  ${n}: cc${g.cc} → ${g.control.label} → ${g.effect}`);
}
console.log('\nORBITS:');
for (const o of result.orbits) {
  const name = o.name ? ` [${o.name}]` : '';
  console.log(`  d${o.n}${name}  sound="${o.sound}"`);
  for (const b of o.bindings) {
    console.log(`    cc${b.cc} → ${b.control.label} → ${b.effect}`);
  }
}
