#!/usr/bin/env node
// Headless CLI wrapper around lib/parser.parse() — runs the HUD parser
// against any .tidal file and prints JSON to stdout. Reuses the babel-free
// ESM-strip loader from spec/smoke.cjs.
//
// Usage:
//   node tools/parse-cli.cjs path/to/track.tidal
// Output: JSON with {file, orbits[], groups, errors}.

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);
}

function main() {
  const arg = process.argv[2];
  if (!arg) {
    console.error('usage: parse-cli.cjs <path/to/track.tidal>');
    process.exit(2);
  }
  const file = path.resolve(arg);
  if (!fs.existsSync(file)) {
    console.error(`not found: ${file}`);
    process.exit(2);
  }

  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 role = loadAsCJS(path.join(libdir, 'role-classifier.js'));
  const parser = loadAsCJS(path.join(libdir, 'parser.js'),
                            { ...lcxl, ...kw, ...role });

  const text = fs.readFileSync(file, 'utf8');
  const result = parser.parse(text);

  // Bolt on a header-comment extract — useful for viz metadata, not part
  // of the HUD parser proper.
  const headerComments = [];
  for (const line of text.split(/\r?\n/)) {
    const m = line.match(/^\s*--\s?(.+?)\s*$/);
    if (m) {
      headerComments.push(m[1]);
      if (headerComments.length >= 12) break;
    } else if (line.trim() && !line.startsWith('--')) {
      break;
    }
  }

  console.log(JSON.stringify({
    file: file,
    header_comments: headerComments,
    groups: result.groups,
    orbits: result.orbits,
    errors: result.errors,
  }, null, 2));
}

main();
