#!/usr/bin/env node -r esm

import path from 'path';
import * as _ from 'lamb';

import {tapValue} from '@svizzle/dev';
import {
	isTsvFile,
	readDirFilesIndexed,
	saveObjPassthrough
} from '@svizzle/file';
import {isIterableEmpty} from '@svizzle/utils';
import {tsvParse} from 'd3-dsv';

import {NUTS_DATABASE_DIR_0, NUTS_DATABASE_DIR_2} from 'paths';

/* paths */

const IN_RECODED_DIR = path.resolve(NUTS_DATABASE_DIR_0, 'history/recoded');
const OUT_CHANGES_PATH = path.resolve(NUTS_DATABASE_DIR_2, 'recodes.json');

/* utils */

const makeRecodes = _.pipe([
	_.mapValuesWith(
		(mapping, filename) => {
			delete mapping.columns;

			return {
				changes: mapping,
				..._.make(
					['from', 'to'],
					filename.split('.')[0].split('_')
				)
			}
		}
	),
	_.values,
	_.sortWith([_.getKey('from')])
]);

const getOldIds = _.pipe([
	_.getKey('changes'),
	_.pluck('oldId'),
]);

const getNewIds = _.pipe([
	_.getKey('changes'),
	_.pluck('newId'),
]);

// const tapIsConsistent = recodes => {
// 	const oldIds = _.flatMapWith(getOldIds)(recodes);
// 	const newIds = _.flatMapWith(getNewIds)(recodes);
// 	const commonIds = _.intersection(oldIds, newIds);
// 	const noCommonIds = isIterableEmpty(commonIds);

// 	if (!noCommonIds) {
// 		console.log(`commonIds: `, commonIds);
// 	}

// 	return recodes;
// };

/* run */

readDirFilesIndexed(IN_RECODED_DIR, isTsvFile, tsvParse)
.then(makeRecodes)
.then(saveObjPassthrough(OUT_CHANGES_PATH))
// .then(tapIsConsistent)
