import { readFile, writeFile, access, mkdir } from 'node:fs/promises'
import path from 'node:path'
import { getRootPath } from '../lib/get-root-path'

export async function tryReadConfig(agent: string): Promise<{
	repeats?: number
	concurrency?: number
} | null> {
	const base = path.dirname(await getRootPath())
	const jsonPath = path.join(base, `${agent}.config.json`)
	try {
		await access(jsonPath)
		const raw = await readFile(jsonPath, 'utf8')
		const obj = JSON.parse(raw)
		return obj
	} catch {
		return null
	}
}

export async function writeConfig(
	agent: string,
	config: { repeats?: number; concurrency?: number }
): Promise<void> {
	const base = path.dirname(await getRootPath())
	const jsonPath = path.join(base, `${agent}.config.json`)
	await mkdir(path.dirname(jsonPath), { recursive: true })
	const body = JSON.stringify(config ?? {}, null, 2)
	await writeFile(jsonPath, body, 'utf8')
}
