import fs, Path = 'path'

export desc = 'Run a Move program.'
export options = [
  'Usage: move run [options] <filename> [..]',
  'Options:',
  ['optimizationLevel',   'Optimization level. Defaults to 0 (basic).',
                          {type: 'int', short: 'O', long: 'optimization-level',
                           def: Move.defaultCompilationOptions.optimizationLevel}],
]

kStdinMaxBufferSize = 1024*1000

export main = ^{
  # Set compilation options
  compileOptions = create Move.defaultCompilationOptions
  compileOptions.optimizationLevel = @parsedOptions.optimizationLevel
  if (@parsedOptions.optimizationLevel > 0)
    compileOptions.outputFormatting = false
    

  if (@argv.length < 1 || @argv[0] == '-') {
    # stdin
    process.stdin.resume()
    process.stdin.setEncoding 'utf8'
    stdinbuf = ''
    process.stdin.on 'data', ^(chunk) {
      stdinbuf += chunk
      if (stdinbuf.length > kStdinMaxBufferSize) {
        process.stdin.close()
        console.error 'fatal: stdin exceeded maximum limit ('+kStdinMaxBufferSize+' bytes)'
        process.exit 1
      }
    }
    process.stdin.on 'end', ^{
      compileOptions.filename = 'stdio:stdin'
      compileOptions.source = stdinbuf
      Move.eval compileOptions
    }
  } else {
    # file on disk
    filename = @argv[0]

    # Resolve absolute path
    try {
      filename = fs.realpathSync filename
    } catch (e) {
      if (e.errno != undefined)
        @program.exit e
      throw e
    }

    process.argv = [process.argv[1]].concat @argv
    # ['move', 'foo/filename.mv', ..]
    #print 'process.argv ->', process.argv
    
    # BUG: Unless the filename has an extension that can be connected to move
    # (i.e. filename is "foo"), Node.js is hard-coded to default to ".js" and
    # thus not triggering our compiler. Seems there's no clean solution for
    # this. Currently, feeding "move run" a filename w/o a move extension will
    # case it to be compiled as JavaScript, which probably will case a SyntaxError.
    
    extname = Path.extname filename
    if (extname && !(extname in require.extensions)) {
      require.extensions[extname] = require.extensions['.mv']
    }

    #process.nextTick ^{
      Move.defaultCompilationOptions = compileOptions
      require filename
    #}
  }
}
