import { Logger } from '@refloat/logger'
import { Command } from 'commander'

import './suppress-warnings'

import { agents } from './agents/agents'
import { Configuration } from './config'
import {
	importWorkspace,
	exportWorkspace,
	exportArtifact,
	importArtifact,
} from './cli/workspace'
import banner from './banner'

export interface Options {
	argv?: string[]
	exitOnError?: boolean
}

export function run({ argv = process.argv, exitOnError = true }: Options = {}) {
	program.parseAsync(argv).catch((error) => {
		if (exitOnError) {
			logger.error('fatal error', { error })

			process.exit(2)
		}
	})
}

const program = new Command('refloat-agent')
const logger = Logger.create('cli')

program
	.version('0.0.1', '-v, --version')
	.description('start an agent')
	.option(
		'-t, --token <token>',
		'setup the agent token (defaults to REFLOAT_TOKEN)',
		process.env.REFLOAT_TOKEN,
	)
	.option(
		'-d, --debug',
		'enable debug logs (enabled if REFLOAT_DEBUG is `true`)',
	)
	.action(async function run(options: any) {
		const config = Configuration.set({
			api: options.api ? new URL(options.api) : undefined,
			token: options.token,
			debug: options.debug,
		})

		console.log(banner)
		logger.debug('starting program', { config })

		await agents()
	})

const commands = {
	import: program.command('import'),
	export: program.command('export'),
}

commands.export
	.command('workspace <build-id> <name> <files...>')
	.action(async (buildId, name, files) =>
		exportWorkspace(files, { buildId, name }),
	)

commands.export
	.command('artifact <step-id> <files...>')
	.option(
		'-n, --name <name>',
		'set the artifact name (defaults to the file name)',
	)
	.action(async (stepId, files, { name }) =>
		exportArtifact(files, { stepId, name }),
	)

commands.import
	.command('workspace <build-id> <name>')
	.action(async (buildId, name) => importWorkspace({ buildId, name }))

commands.import
	.command('artifact <build-id> <file>')
	.action(async (buildId, file) => importArtifact(file, { buildId }))
