import {
  CliLeaf,
  CliUsageError,
  CliStringInput,
  CliFlagInput
} from '@alwaysai/alwayscli';
import {
  yesCliInput,
  targetProtocolCliInput,
  targetHardwareCliInput,
  targetHostnameCliInput,
  targetPathCliInput
} from '../../cli-inputs';
import { appConfigureComponent } from '../../components/app';
import { TargetProtocol } from '../../core/app';
import { ALWAYSAI_OS_PLATFORM } from '../../environment';
import { NotAllowedWithMessage } from '../../util';

export const appConfigureCliLeaf = CliLeaf({
  name: 'configure',
  description: 'Configure this directory as an alwaysAI application',
  namedInputs: {
    yes: yesCliInput,
    protocol: targetProtocolCliInput,
    hardware: targetHardwareCliInput,
    hostname: targetHostnameCliInput,
    path: targetPathCliInput,
    project: CliStringInput({
      description: 'Project ID'
    }),
    deviceId: CliStringInput({
      description: 'Project specific device'
    }),
    'sync-models': CliFlagInput({
      description: 'Pulls project models to local application'
    })
  },
  async action(
    _,
    {
      yes,
      protocol,
      hardware,
      hostname,
      path,
      project,
      deviceId,
      'sync-models': syncModels
    }
  ) {
    // Preliminary checks that don't help us with type narrowing
    if (protocol === 'docker:' && ALWAYSAI_OS_PLATFORM !== 'linux') {
      throw new CliUsageError(
        `Option "protocol" is not allowed to have value "${TargetProtocol['docker:']}" if your operating system platform is "${ALWAYSAI_OS_PLATFORM}"`
      );
    }

    if (protocol === 'docker:' && hostname) {
      throw new CliUsageError(
        NotAllowedWithMessage('hostname', 'protocol', TargetProtocol['docker:'])
      );
    }

    if (protocol === 'docker:' && path) {
      throw new CliUsageError(
        NotAllowedWithMessage('path', 'protocol', TargetProtocol['docker:'])
      );
    }

    return await appConfigureComponent({
      yes,
      targetProtocol: protocol,
      targetHardware: hardware,
      targetHostname: hostname,
      targetPath: path,
      project,
      deviceId,
      syncModels
    });
  }
});
