#!/usr/bin/env node
import { VERSION, runRead, doctor } from './agent-core.mjs';

const usage = 'Brand Design Ltd. agent CLI ' + VERSION + '\n' +
  'Node.js 22+; download branddesign-agent.mjs and agent-core.mjs into the same directory.\n' +
  'Usage: node branddesign-agent.mjs <discover|services|service ID|pricing|catalog|evidence|capabilities|doctor>\n' +
  'JSON output. Exit 0: success; 1: retrieval/integrity failure; 2: invalid invocation.\n' +
  'Public GET only. No authentication, registration, orders, payment or persistent memory writes.\n';
const args = process.argv.slice(2);
if (args.length === 1 && ['--help','-h'].includes(args[0])) {
  process.stdout.write(usage);
} else if (args.length === 1 && args[0] === '--version') {
  process.stdout.write(VERSION + '\n');
} else if (!['discover','services','service','pricing','catalog','evidence','capabilities','doctor'].includes(args[0]) ||
           args.length !== (args[0] === 'service' ? 2 : 1) ||
           (args[0] === 'service' && !/^[a-z0-9][a-z0-9-]{0,79}$/.test(args[1]))) {
  process.stderr.write(usage); process.exitCode = 2;
} else {
  try {
    const result = args[0] === 'doctor' ? await doctor() :
      await runRead(args[0], args[0] === 'service' ? {id:args[1]} : {});
    process.stdout.write(JSON.stringify(result,null,2) + '\n');
    if (result.ok === false) process.exitCode = 1;
  } catch (error) {
    process.stderr.write(JSON.stringify({ok:false,error:error.message,readOnly:true}) + '\n');
    process.exitCode = 1;
  }
}
