/*
 * Copyright (C) 2022 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {readFileSync, writeFileSync} from 'fs';
import {omit, pickBy} from '@openstapps/collection-utils';

/**
 * accumulate and transform licenses based on two license files
 * @param {string} path
 * @param {string} additionalLicensesPath
 */
function accumulateFile(path, additionalLicensesPath) {
  const packageJson = JSON.parse(readFileSync('./package.json').toString());
  const dependencies = packageJson.dependencies;

  console.log(`Accumulating licenses from ${path}`);

  writeFileSync(
    path,
    JSON.stringify(
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      Object.entries({
        ...pickBy(JSON.parse(readFileSync(path).toString()), (_, key) => {
          const parts = /** @type {string} */ (key).split('@');

          return dependencies[parts.slice(0, -1).join('@')] === parts[parts.length - 1];
        }),
        ...JSON.parse(readFileSync(additionalLicensesPath).toString()),
      })
        .map(([key, value]) => ({
          licenseText: value.licenseFile && readFileSync(value.licenseFile, 'utf8'),
          name: key,
          ...omit(value, 'licenseFile', 'path'),
        }))
        .sort((a, b) => a.name.localeCompare(b.name)),
    ),
  );
}

accumulateFile('./src/assets/about/licenses.json', './additional-licenses.json');
