#!/usr/bin/env node
/**
 * Vincent Socci public discovery CLI.
 * https://vinsocci.com/developers
 *
 *   npx vinsocci profile
 *   npx vinsocci insights
 *   npx vinsocci insights ai-governance-for-brokerages
 *   npx vinsocci health
 *   npx vinsocci openapi
 */
const BASE = (process.env.VINSOCCI_BASE_URL || "https://vinsocci.com").replace(
  /\/$/,
  ""
);

const COMMANDS = {
  profile: "/api/v1/profile",
  health: "/api/v1/health",
  index: "/api/v1",
  openapi: "/openapi.json",
  catalog: "/.well-known/api-catalog",
};

function usage(code = 0) {
  const text = `vinsocci: Vincent Socci public API CLI

Usage:
  vinsocci <command> [slug]

Commands:
  profile              GET /api/v1/profile
  insights [slug]      list insights, or one insight by slug
  health               GET /api/v1/health
  index                GET /api/v1
  openapi              GET /openapi.json
  catalog              GET /.well-known/api-catalog
  help                 this message

Env:
  VINSOCCI_BASE_URL    default https://vinsocci.com

Docs: https://vinsocci.com/developers
`;
  process.stdout.write(text);
  process.exit(code);
}

async function get(path) {
  const res = await fetch(`${BASE}${path}`, {
    headers: { Accept: "application/json", "User-Agent": "vinsocci-cli/1.0" },
  });
  const text = await res.text();
  if (!res.ok) {
    process.stderr.write(`HTTP ${res.status} ${path}\n${text}\n`);
    process.exit(1);
  }
  try {
    process.stdout.write(JSON.stringify(JSON.parse(text), null, 2) + "\n");
  } catch {
    process.stdout.write(text.endsWith("\n") ? text : text + "\n");
  }
}

const [, , cmd, arg] = process.argv;
if (!cmd || cmd === "help" || cmd === "--help" || cmd === "-h") usage(0);

if (cmd === "insights") {
  const path = arg ? `/api/v1/insights/${encodeURIComponent(arg)}` : "/api/v1/insights";
  await get(path);
} else if (COMMANDS[cmd]) {
  await get(COMMANDS[cmd]);
} else {
  process.stderr.write(`Unknown command: ${cmd}\n\n`);
  usage(1);
}
