#!/usr/bin/env node

const readline = require('readline');
const enrichment = require("../main");
const fs = require("fs");

const rl = readline.createInterface({
  input: process.argv.length < 3 ? process.stdin : fs.createReadStream(process.argv[2], 'UTF-8'),
  crlfDelay: Infinity
});

let mode = 0;

const lines = [];

rl.on('line', (line) => {
  if (mode === 0) {
    try {
      JSON.parse(line);
      mode = 2;
    } catch (e) {
      mode = 1;
    }

  }
  switch (mode) {
    case 1:
      lines.push(line);
      break;
    case 2:
      try {
        const json = JSON.parse(line);
        const done = enrichment(json);
        console.log(JSON.stringify(done));
      } catch (e) {
        console.log(`# error ${e.toString()}`)
      }
      break;
  }
}).on('close', () => {
  if (mode === 1) {
    try {
      const json = JSON.parse(lines.join("\n"));
      const done = enrichment(json);
      console.log(JSON.stringify(done, null, 2));
    } catch (e) {
      console.log(`# error ${e.toString()}`)
    }
  }
});
