import { CliTerseError } from '@alwaysai/alwayscli';
import { APP_JSON_FILE_NAME } from '../../../paths';
import { AppJsonFile } from '../../../core/app';
import { ProjectJsonFile } from '../../../core/project';
import { getModels } from '../../../core/model';
import { checkConfigFileExistsAndValid } from '../../../util/config-file-exists-and-is-valid';

export async function checkForInvalidModelsComponent() {
  // Retrieve list of models and versions from the $APP_JSON_FILE_NAME
  const appJsonFile = AppJsonFile();

  if (!(await checkConfigFileExistsAndValid(appJsonFile))) {
    throw new CliTerseError(
      `Application does not have a valid ${APP_JSON_FILE_NAME} file.`
    );
  }
  const appJson = appJsonFile.read();
  const {
    project: { id }
  } = ProjectJsonFile().read();
  const projectJsonModels = appJson.models;
  // Retrieve list of models and versions from the RPC
  const userModels: { [key: string]: number } = {};
  (await getModels({ yes: true, projectUuid: id })).forEach((modelEntry) => {
    userModels[modelEntry['id']] = modelEntry['version'];
  });
  // Compare the lists and collect models that are either missing or have mismatched versions
  const invalidModels: { [key: string]: number } = {};
  for (const projectModel in projectJsonModels) {
    // Check if model is missing
    if (!userModels[projectModel]) {
      invalidModels[projectModel] = projectJsonModels[projectModel];
    }
    const expectedVersion = projectJsonModels[projectModel];
    const actualVersion = userModels[projectModel];

    // Check if the model version doesn't match
    if (actualVersion < expectedVersion) {
      invalidModels[projectModel] = projectJsonModels[projectModel];
    }
  }
  return invalidModels;
}
