#!/usr/bin/env node
/**
 * Zone Healthy public CLI.
 * Install: curl -fsSL https://www.zonehealthy.com/cli/zh -o zh && chmod +x zh
 * Usage: zh health | zh site | zh markdown [path]
 */
const DEFAULT_BASE = 'https://www.zonehealthy.com'

function parseArgs(argv) {
  const args = argv.slice(2)
  let base = process.env.ZONEHEALTHY_URL || DEFAULT_BASE
  const rest = []
  for (let i = 0; i < args.length; i += 1) {
    if (args[i] === '--base' && args[i + 1]) {
      base = args[i + 1]
      i += 1
    } else {
      rest.push(args[i])
    }
  }
  return { base: base.replace(/\/$/, ''), command: rest[0] || 'help', operand: rest[1] }
}

export function usage() {
  return `zh — Zone Healthy public CLI

When to use this: script Southern California meal-plan lookup, API health, and Markdown page fetch without a browser.

Commands:
  zh health              GET /api/v1/health
  zh site                GET /api/v1/site
  zh markdown [path]     GET path with Accept: text/markdown (default /)
  zh --base URL <cmd>    Override origin (default ${DEFAULT_BASE})

Install from the official site (no npm login required):
  curl -fsSL https://www.zonehealthy.com/cli/zh -o zh && chmod +x zh
`
}

export async function runCli(argv, fetchImpl = fetch) {
  const { base, command, operand } = parseArgs(argv)
  if (command === 'help' || command === '--help' || command === '-h') {
    return { status: 0, stdout: usage(), stderr: '' }
  }
  if (!['health', 'site', 'markdown'].includes(command)) {
    return { status: 1, stdout: '', stderr: `Unknown command: ${command}\n${usage()}` }
  }
  const path =
    command === 'health'
      ? '/api/v1/health'
      : command === 'site'
        ? '/api/v1/site'
        : operand || '/'
  const accept = command === 'markdown' ? 'text/markdown' : 'application/json'
  const response = await fetchImpl(`${base}${path.startsWith('/') ? path : `/${path}`}`, {
    headers: { Accept: accept },
  })
  const text = await response.text()
  return {
    status: response.ok ? 0 : 1,
    stdout: text.endsWith('\n') ? text : `${text}\n`,
    stderr: '',
  }
}

const isMain =
  typeof process !== 'undefined' &&
  process.argv[1] &&
  (process.argv[1].endsWith('/zh') ||
    process.argv[1].endsWith('/zhCli.mjs') ||
    process.argv[1].endsWith('zh.mjs'))

if (isMain) {
  runCli(process.argv)
    .then(({ status, stdout, stderr }) => {
      if (stdout) process.stdout.write(stdout)
      if (stderr) process.stderr.write(stderr)
      process.exit(status)
    })
    .catch((error) => {
      console.error(error)
      process.exit(1)
    })
}
