#!/usr/bin/env node

const argv = require('minimist')(process.argv.slice(2))
const dedent = require('dedent')
const JsonStreamStringify = require('json-stream-stringify')
const { schemas, getSchema, getOperations } = require('..')

main()

async function main () {
  const command = argv._[0]
  const schemaName = argv.schemaName
  let schema, operations, stream

  switch (command) {
    case 'operations':
      schema = await getSchema(schemaName)
      operations = await getOperations(schema)
      stream = new JsonStreamStringify(operations)
      stream.pipe(process.stdout)
      break
    case 'schema':
      schema = await getSchema(schemaName)
      stream = new JsonStreamStringify(schema)
      stream.pipe(process.stdout)
      break
    default:
      help()
  }
}

function help () {
  console.log(dedent`
    Usage:

    # Print JSON schema to STDOUT
    $ github-openapi schema

    # Specify a different schema
    $ github-openapi schema --schemaName=ghe-2.19-deref

    # List operations as a JSON array
    $ github-openapi operations

    # Specify a different schema
    $ github-openapi operations --schemaName=ghe-2.19-deref

    # Allowable values for 'schema':
    - ${Object.keys(schemas).join('\n- ')}
  `)
  process.exit()
}
