///|
/// Entry point for the native command-line adapter.
/// Run with `moon run cmd/main` from the project root.
fn main {
  let parsed = @brandbook.parse_cli(@brandbook.cli_user_args(@env.args()))
  match parsed.request {
    Some(request) => {
      let input = read_cli_input(request)
      if request.input_path != "" && input is None {
        @sys.exit(2)
      }
      let result = @brandbook.run_cli(request, input)
      let output_ok = if result.exit_code == 0 && request.output != "" {
        write_cli_output(request.output, result.output)
      } else {
        println(result.output)
        true
      }
      let exit_code = if output_ok { result.exit_code } else { 2 }
      @sys.exit(exit_code)
    }
    None => {
      for error in parsed.errors {
        println("error: " + error)
      }
      println(@brandbook.cli_help())
      @sys.exit(2)
    }
  }
}

///|
fn read_cli_input(request : @brandbook.CliRequest) -> String? {
  if request.input_path != "" {
    Some(@fs.read_file_to_string(request.input_path)) catch {
      @fs.IOError(message) => {
        println(
          "error: cannot read input file '" +
          request.input_path +
          "': " +
          message,
        )
        None
      }
    }
  } else if request.input == "" {
    None
  } else {
    Some(request.input)
  }
}

///|
fn write_cli_output(path : String, content : String) -> Bool {
  try {
    @fs.write_string_to_file(path, content)
    println("wrote " + path)
    true
  } catch {
    @fs.IOError(message) => {
      println("error: cannot write output file '" + path + "': " + message)
      false
    }
  }
}