import { Logger } from '@refloat/logger'

import { APIClient } from '../api/api-client'
import { APIQueue } from '../api/api-queue'
import { Graph } from '../run/graph'
import { Scheduler } from '../run/scheduler'
import { AbortContext } from '../utils/abort-context'
import { sleep } from '../utils/sleep'

const logger = Logger.create('build-agent')

export async function runAgent(
	ctx: AbortContext,
	api: APIClient,
	queue = new APIQueue(api),
) {
	const scheduler = new Scheduler(queue)

	logger.info('waiting for jobs')

	await queue.wait(async () => {
		try {
			while (ctx.running && queue.running) {
				const job = await api.acquireJob()

				if (job) {
					try {
						logger.info('running', { job: job.path })

						await scheduler.run(Graph.from(job))

						logger.info('completed', { job: job.path })
					} catch (error) {
						logger.error('failed', { job: job.path, error })
					}
				} else {
					await ctx.wait(sleep(1000))
				}
			}
		} finally {
			queue.running = false
		}
	})
}
