#!/usr/bin/env node
/**
 * Node.js WASM Runner for tinySQL
 */

const fs = require('fs');
const path = require('path');
require('./wasm_exec.js');

async function main() {
  const wasmPath = path.join(__dirname, 'tinySQL.wasm');
  const go = new Go();
  const wasmBuffer = fs.readFileSync(wasmPath);
  const { instance } = await WebAssembly.instantiate(wasmBuffer, go.importObject);

  // The module deliberately remains alive to serve its JS API, so do not
  // await go.run(): it resolves only after the runtime exits. Wait for the
  // exported API instead.
  go.run(instance).catch(err => {
    console.error('tinySQL WASM runtime failed:', err);
    process.exit(1);
  });
  for (let attempt = 0; attempt < 100 && !global.tinySQL; attempt++) {
    await new Promise(resolve => setTimeout(resolve, 10));
  }

  if (!global.tinySQL) {
    console.error('tinySQL API not available');
    process.exit(1);
  }

  const db = global.tinySQL;
  console.log('Opening DB...');
  console.log(db.open('mem://?tenant=default'));

  const args = process.argv.slice(2);
  const cmd = args[0] || 'status';
  const sql = args.slice(1).join(' ');

  // db.* calls now return native JS objects/arrays directly (via
  // syscall/js.ValueOf on the Go side) instead of JSON strings, so no
  // JSON.parse round trip is needed here any more.
  switch (cmd) {
    case 'exec':
      console.log(db.exec(sql));
      break;
    case 'query':
      const res = db.query(sql);
      console.log(res);
      if (res && res.columns && res.rows) {
        console.table(res.rows.map(r => Object.fromEntries(res.columns.map((c,i)=>[c,r[i]]))));
      }
      break;
    case 'status':
    default:
      console.log(db.status());
  }

  console.log(db.close());
}

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