#!/usr/bin/env node
// Drop-in replacement for /root/hermes-router.py — IDENTICAL CLI contract:
//   tsx mastra-router.ts <sender> <message...>   ->  one-line JSON {action, ...}
// Shares the exact same lib/config as the Mastra workflow (single source of truth).
import { resolve } from './src/mastra/lib/resolve';
import { getContext } from './src/mastra/lib/hermesConfig';
import { compose } from './src/mastra/lib/compose';

async function main() {
  const argv = process.argv.slice(2);
  if (argv.length < 1) {
    console.log(JSON.stringify({ error: 'usage: mastra-router.ts <sender> <message...>' }));
    return;
  }
  const sender = argv[0];
  const msg = argv.slice(1).join(' ') || '(fara text)';

  const persona = resolve(sender);
  const tier = persona.tier;

  if (tier === 'block' || tier === 'ignore') {
    console.log(JSON.stringify({ action: 'ignore', tier, sender }));
    return;
  }

  const ctx = getContext();
  const { reply, ok } = await compose(persona, ctx, msg);

  if (tier === 'draft') {
    console.log(JSON.stringify({ action: 'draft_to_adrian', persona: persona.name, suggested: reply, ok, ctx: ctx.time_window }));
  } else if (ok) {
    console.log(JSON.stringify({ action: 'send_to_contact', persona: persona.name, reply, ctx: ctx.time_window }));
  } else {
    console.log(JSON.stringify({ action: 'escalate_to_adrian', persona: persona.name, reason: 'model output slab/degenerat - raspunde manual', ctx: ctx.time_window }));
  }
}

// Mastra's OpenRouter client leaves a dangling keep-alive handle that prevents
// natural exit; force it so the CLI returns immediately after printing (it's a
// one-shot drop-in, exactly like hermes-router.py which exits cleanly).
main()
  .then(() => process.exit(0))
  .catch((e) => {
    console.error(e);
    process.exit(1);
  });
