#!/usr/bin/env node

const { readFileSync, writeFileSync } = require('fs')
const { basename } = require('path')

const DEFAULT_SCHEMES_FILE = '/usr/share/lebiniou/etc/schemes.json'
const arg = process.argv[2]

if (arg === '-h' || arg === '--help') {
  console.log(`Usage: node schemes.json [file] (default: '${DEFAULT_SCHEMES_FILE}')`)
  return
}

const schemesFile = process.argv[2] || DEFAULT_SCHEMES_FILE

const js = JSON.parse(readFileSync(schemesFile))

const parse = opts => opts.map(opt => ' ' + opt.slice(3))

js.sort((a, b) => a.plugins.length > b.plugins.length ? 1 : - 1)
js.map((scheme, idx) => {
  const plugins = scheme.plugins
  opts = plugins.map(plugin => {
    return plugin.proba ? `${parse(plugin.options)} (${plugin.proba})` : `${parse(plugin.options)}`
  })
  console.log(`${("00" + idx).slice(-3)} (${opts.length})${opts}`)
})

const outFile = basename(schemesFile, '.json') + '_new.json'
writeFileSync(outFile, JSON.stringify(js, null, 2))
console.log('File saved as', outFile)
