import path from 'node:path'

import inquirer from 'inquirer'
import { command } from 'execa'

import {
  NODEJS_BRIDGE_SRC_PATH,
  PYTHON_BRIDGE_SRC_PATH,
  PYTHON_TCP_SERVER_SRC_PATH
} from '@/constants'
import { LogHelper } from '@/helpers/log-helper'
import { LoaderHelper } from '@/helpers/loader-helper'

/**
 * Pre-release binaries via GitHub Actions
 * 1. Ask for confirmation whether the binary version has been bumped
 * 2. Trigger GitHub workflow to pre-release binaries
 */

const BUILD_TARGETS = new Map()

BUILD_TARGETS.set('nodejs-bridge', {
  workflowFileName: 'pre-release-nodejs-bridge.yml',
  versionFilePath: path.join(NODEJS_BRIDGE_SRC_PATH, 'version.ts')
})
BUILD_TARGETS.set('python-bridge', {
  workflowFileName: 'pre-release-python-bridge.yml',
  versionFilePath: path.join(PYTHON_BRIDGE_SRC_PATH, 'version.py')
})
BUILD_TARGETS.set('tcp-server', {
  workflowFileName: 'pre-release-tcp-server.yml',
  versionFilePath: path.join(PYTHON_TCP_SERVER_SRC_PATH, 'version.py')
})
;(async () => {
  LoaderHelper.start()

  const { argv } = process
  const givenReleaseTarget = argv[2].toLowerCase()
  const givenBranch = argv[3]?.toLowerCase()
  const { workflowFileName, versionFilePath } =
    BUILD_TARGETS.get(givenReleaseTarget)

  LoaderHelper.stop()
  const answer = await inquirer.prompt({
    type: 'confirm',
    name: 'binary.bumped',
    message: `Have you bumped the version number of the binary from the "${versionFilePath}" file?`,
    default: false
  })
  LoaderHelper.start()

  if (!answer.binary.bumped) {
    LogHelper.info(
      'Please bump the version number of the binary from the version file before continuing'
    )
    process.exit(0)
  }

  try {
    LogHelper.info('Triggering the GitHub workflow...')

    const runWorkflowCommand = !givenBranch
      ? `gh workflow run ${workflowFileName}`
      : `gh workflow run ${workflowFileName} --ref ${givenBranch}`

    await command(runWorkflowCommand, {
      shell: true,
      stdout: 'inherit'
    })

    LogHelper.success(
      'GitHub workflow triggered. The pre-release is on its way!'
    )
    LogHelper.success(
      'Once the pre-release is done, go to the GitHub releases to double-check information and hit release'
    )

    process.exit(0)
  } catch (e) {
    LogHelper.error(
      `An error occurred while triggering the GitHub workflow: ${e}`
    )
    process.exit(1)
  }
})()
