import { CliTerseError } from '@alwaysai/alwayscli';
import * as logSymbols from 'log-symbols';
import { modelPackageCloudClient } from '../../core/model';
import { CliRpcClient } from '../../infrastructure';
import { echo, logger, runWithSpinner, stringifyError } from '../../util';
import { validatePackageComponent } from '../../subcommands/model/validate-package';
import { ModelPackageJsonFile } from '../../core/model/model-package-json-file';

export async function modelPublishComponent(props: { force?: boolean }) {
  const { force } = props;
  try {
    if (!(await validatePackageComponent(process.cwd())) && !force) {
      throw new CliTerseError(
        `Model has configuration errors! Please resolve them and try again.`
      );
    }
    // Read parsed JSON here to allow publishing when validation fails
    // This makes validation errors into warnings when `force` is set
    const modelJson = ModelPackageJsonFile(process.cwd()).readParsed();
    const { id } = modelJson;
    await runWithSpinner(
      async () => {
        await modelPackageCloudClient.publish();
      },
      [],
      'Publish model to cloud'
    );
    const { version: latestVersion } = await CliRpcClient().getModelVersion({
      id
    });
    echo(`${logSymbols.success} Published ${id} version ${latestVersion}`);
  } catch (exception) {
    logger.error(stringifyError(exception));
    throw new CliTerseError(exception.message);
  }
}
