import * as plugins from './mod.plugins.js';
import * as paths from '../paths.js';

import { logger } from '../gitzone.logging.js';
import { Project } from '../classes.project.js';

export const run = async (projectArg: Project) => {
  // lets care about tsconfig.json
  logger.log('info', 'Formatting tsconfig.json...');
  const tsconfigSmartfile = await plugins.smartfile.SmartFile.fromFilePath(
    plugins.path.join(paths.cwd, 'tsconfig.json'),
  );
  const tsconfigObject = JSON.parse(tsconfigSmartfile.contentBuffer.toString());
  tsconfigObject.compilerOptions = tsconfigObject.compilerOptions || {};
  tsconfigObject.compilerOptions.baseUrl = '.';
  tsconfigObject.compilerOptions.paths = {};
  const tsPublishMod = await import('@git.zone/tspublish');
  const tsPublishInstance = new tsPublishMod.TsPublish();
  const publishModules = await tsPublishInstance.getModuleSubDirs(paths.cwd);
  for (const publishModule of Object.keys(publishModules)) {
    const publishConfig = publishModules[publishModule];
    tsconfigObject.compilerOptions.paths[`${publishConfig.name}`] = [`./${publishModule}/index.js`];
  }
  tsconfigSmartfile.setContentsFromString(JSON.stringify(tsconfigObject, null, 2));
  await tsconfigSmartfile.write();
};