#!/usr/bin/env node

/** Reads a .dval file (stored data under the Reactor `storage` directory) and converts the
 *  contents to standard JSON. Not all data stored in .dval files can be converted to JSON,
 *  because dval supports data types and structures that JSON does not. In that case, this
 *  tool will automatically switch to a JSON-like alternate format that is still human-
 *  readable. However, this alternate format is not parseable as JSON.
 */

const version = 25337;

const fs = require('fs');
const path = require('path');
const { inspect } = require('node:util');

const devalue = require( "devalue" );

// console.log(process.argv);
if ( process.argv.length < 3 ) {
    console.log( `Usage: node ${process.argv[1]} <input-dval-file> [<output-json-file>]` );
    console.log( `       Output is to stdout if the <output-json-file> is not given.` );
    process.exit(255);
}

let data;
try {
    data = fs.readFileSync( process.argv[2] );
} catch ( err ) {
    console.error( `Can't read ${process.argv[2]}: ${err.message}` );
    process.exit(1);
}
let inb = data.length;
try {
    data = devalue.parse( data );
} catch ( err ) {
    console.error( "Error:", err.message );
    console.error( "Make sure the input file is a .dval file" );
    process.exit(2);
}
try {
    data = JSON.stringify(data, undefined, 4);
} catch ( err ) {
    console.error("The input file could not be converted to standard JSON; switching to alternate format.");
    data = inspect( data, {
        colors: false,       // or true if you want ANSI colors in terminals
        depth: null,         // null = no depth limit (default is 2 for console.log)
        showHidden: false,   // show non-enumerable properties
        compact: false,      // false = pretty-print with newlines (like console.log)
        breakLength: Infinity,  // when to break lines
        maxArrayLength: null,
        maxStringLength: null,
        sorted: true,        // sort object keys
    });
}
if ( process.argv.length > 3 && "-" !== process.argv[3] ) {
    fs.writeFileSync( process.argv[3], data );
    console.log("Read", inb, "from", process.argv[2], "wrote", data.length, "to", process.argv[3]);
} else {
    console.log( data );
}
