#!/usr/bin/env node
// CLI counterpart to dev-server.js. Calls the local dev server's HTTP API.
// Usage:
//   node scripts/dev-cli.js onboard "Test User"
//   node scripts/dev-cli.js tick 8
//   node scripts/dev-cli.js say "Yes"
//   node scripts/dev-cli.js ff 1d
//   node scripts/dev-cli.js webhook L03
//   node scripts/dev-cli.js state
//   node scripts/dev-cli.js reset

const PORT = process.env.PORT || 7331;
const BASE = `http://127.0.0.1:${PORT}`;

const [, , cmd, ...rest] = process.argv;

async function post(path, body) {
  const r = await fetch(BASE + path, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body || {}),
  });
  return r.json();
}
async function get(path) {
  const r = await fetch(BASE + path);
  return r.json();
}

const ms = { d: 86_400_000, h: 3_600_000, w: 604_800_000 };
function parseDur(s) {
  const m = /^(\d+)([dhw])$/.exec(s);
  return m ? Number(m[1]) * ms[m[2]] : Number(s);
}

(async () => {
  switch (cmd) {
    case 'onboard': console.log(await post('/dev/onboard', { name: rest.join(' ') || 'Test User' })); break;
    case 'tick':    console.log(await post('/dev/tick', { slot: Number(rest[0]) || 8 })); break;
    case 'say':     console.log(await post('/dev/say', { text: rest.join(' ') })); break;
    case 'ff':      console.log(await post('/dev/ff', { ms: parseDur(rest[0] || '1d') })); break;
    case 'webhook': console.log(await post('/dev/webhook', { lessonId: rest[0] || 'L01' })); break;
    case 'reset':   console.log(await post('/dev/reset')); break;
    case 'state':   console.log(JSON.stringify(await get('/dev/state'), null, 2)); break;
    default:
      console.log('cmds: onboard <name> | tick <8|14|18> | say <text> | ff <1d|6h|2w|ms> | webhook <Lxx> | state | reset');
  }
})().catch(e => { console.error(e); process.exit(1); });
