import type { TestAgentFactory } from '@recombine-ai/engine'
import path from 'node:path'
import { pathToFileURL } from 'node:url'

export interface Project {
	factories: Record<string, TestAgentFactory>
	basePath: string
}

export async function getAgentFactories(agentsModule: string) {
	const modUrl = pathToFileURL(agentsModule).href

	let mod: any
	try {
		mod = await import(modUrl)
	} catch (e) {
		console.error('Failed to import agents module:', modUrl, e)
	}

	const basePath = mod?.basePath ?? path.dirname(agentsModule)
	if (!mod?.basePath) {
		console.warn(`Agents module does not export basePath; falling back to ${basePath}.`)
	}

	if (!mod?.default) {
		throw new Error(`Cannot load agents from ${agentsModule}`)
	}

	return {
		basePath,
		factories: mod.default as Record<string, TestAgentFactory>
	}
}
