import { Logger } from '@refloat/logger'

import { APIClient } from '../api/api-client'
import { Configuration } from '../config'
import { AgentPlatform } from '../generated/schema'
import version from '../generated/version'
import { AbortContext } from '../utils/abort-context'
import { configAgent } from './config-agent'
import { runAgent } from './build-agent'

const logger = Logger.create('agents')

export async function agents() {
	const config = Configuration.get()
	const api = new APIClient(config.api)
	const ctx = new AbortContext()

	logger.info('registering', {
		platform: config.platform,
		name: config.name,
		version,
	})

	const { agent } = await api.register(config)

	logger.info('registered', {
		id: agent.id,
		org: agent.org.slug,
		tags: agent.tags,
	})

	await Promise.all([
		runAgent(ctx, api),
		Promise.resolve().then(async () => {
			if (
				config.platform === AgentPlatform.Linux ||
				config.platform === AgentPlatform.macOS
			) {
				await configAgent(ctx, api)
			}
		}),
	])
}
