#!/usr/bin/env node

/**
 * Thin npm wrapper for the Horizon SDK CLI.
 *
 * Delegates to the Python `horizon` CLI via:
 *   1. `horizon` (if already installed via pip/uv)
 *   2. `uvx horizon-sdk` (zero-install via uv)
 *   3. `pipx run horizon-sdk` (fallback)
 *
 * Usage:
 *   bunx horizon-sdk discover "election"
 *   npx horizon-sdk top-markets --json
 */

import { execFileSync, execSync } from "node:child_process";

const args = process.argv.slice(2);

function tryRun(cmd, cmdArgs) {
  try {
    execFileSync(cmd, cmdArgs, { stdio: "inherit" });
    return true;
  } catch (e) {
    if (e.status !== null) process.exit(e.status);
    return false;
  }
}

function commandExists(cmd) {
  try {
    execSync(`command -v ${cmd}`, { stdio: "ignore" });
    return true;
  } catch {
    return false;
  }
}

// 1. Try direct `horizon` command (already installed)
if (commandExists("horizon")) {
  tryRun("horizon", args);
  process.exit(0);
}

// 2. Try `uvx horizon-sdk` (zero-install, fastest)
if (commandExists("uvx")) {
  if (tryRun("uvx", ["horizon-sdk", ...args])) process.exit(0);
}

// 3. Try `pipx run horizon-sdk`
if (commandExists("pipx")) {
  if (tryRun("pipx", ["run", "horizon-sdk", ...args])) process.exit(0);
}

// 4. Nothing worked
console.error(`
  horizon-sdk requires Python. Install with one of:

    uv tool install horizon-sdk     # recommended
    pip install horizon-sdk
    pipx install horizon-sdk

  Or install uv first: https://docs.astral.sh/uv/getting-started/installation/
`);
process.exit(1);
