import { existsSync, readFileSync, readdirSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
export function loadAgentDefinitionsFromDisk(cwd) {
    const directories = [
        resolve(homedir(), ".best-agent", "agents"),
        resolve(findRuntimeProjectRoot(cwd), ".best-agent", "agents"),
    ];
    const profiles = [];
    const seen = new Set();
    for (const directory of directories) {
        if (!existsSync(directory)) {
            continue;
        }
        for (const entry of readdirSync(directory)) {
            if (!entry.endsWith(".json")) {
                continue;
            }
            const path = join(directory, entry);
            try {
                const parsed = JSON.parse(readFileSync(path, "utf8"));
                if (!parsed ||
                    typeof parsed !== "object" ||
                    Array.isArray(parsed) ||
                    typeof parsed.name !== "string" ||
                    typeof parsed.description !== "string") {
                    continue;
                }
                const index = profiles.findIndex((candidate) => candidate.name === parsed.name);
                if (index >= 0) {
                    profiles[index] = parsed;
                }
                else if (!seen.has(parsed.name)) {
                    profiles.push(parsed);
                }
                seen.add(parsed.name);
            }
            catch {
                continue;
            }
        }
    }
    return profiles;
}
function findRuntimeProjectRoot(cwd) {
    let current = resolve(cwd);
    while (true) {
        if (existsSync(join(current, ".git"))) {
            return current;
        }
        const parent = dirname(current);
        if (parent === current) {
            return resolve(cwd);
        }
        current = parent;
    }
}
//# sourceMappingURL=agent-definition-loader.js.map