import { listMachines } from './machines.ts'
import type { FlyMachinesInput } from './types.ts'
/**
* Count Fly machines and group totals by state and app name.
* @returns Aggregate counts plus the underlying machine list.
* @example
* import machineCount from 'kody:@kody/fly/machine-count'
* const result = await machineCount({ organizationSlug: 'my-org' })
* // => { count: 12, byState: { started: 10 }, byApp: { my-app: 4 }, ... }
*/
export default async function machineCount(params: FlyMachinesInput = {}) {
const result = await listMachines(params)
const byState: Record<string, number> = {}
const byApp: Record<string, number> = {}
for (const machine of result.machines) {
const state = machine.state || 'unknown'
const app = machine.app?.name || machine.app?.id || 'unknown'
byState[state] = (byState[state] || 0) + 1
byApp[app] = (byApp[app] || 0) + 1
}
return { count: result.count, byState, byApp, machines: result.machines }
}