import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
/**
 * Discover all contexts with .ai/CONTEXT.md (root + immediate children).
 * Optionally filter by target name.
 */
export function discoverContexts(rootDir, targetFilter) {
    const contexts = [];
    const rootAiDir = join(rootDir, '.ai');
    const rootContextFile = join(rootAiDir, 'CONTEXT.md');
    if (existsSync(rootContextFile) && !targetFilter) {
        contexts.push({
            aiDir: rootAiDir,
            contextDir: rootDir,
            contextFile: rootContextFile,
            hasAgents: existsSync(join(rootAiDir, 'agents')),
            hasCommands: existsSync(join(rootAiDir, 'commands')),
            hasSkills: existsSync(join(rootAiDir, 'skills')),
            isRoot: true,
            name: 'root',
        });
    }
    const entries = readdirSync(rootDir, { withFileTypes: true });
    for (const entry of entries) {
        if (!entry.isDirectory())
            continue;
        if (entry.name.startsWith('.') || entry.name === 'node_modules')
            continue;
        if (targetFilter && entry.name !== targetFilter)
            continue;
        const childDir = join(rootDir, entry.name);
        const childAiDir = join(childDir, '.ai');
        const childContextFile = join(childAiDir, 'CONTEXT.md');
        if (!existsSync(childContextFile))
            continue;
        contexts.push({
            aiDir: childAiDir,
            contextDir: childDir,
            contextFile: childContextFile,
            hasAgents: existsSync(join(childAiDir, 'agents')),
            hasCommands: existsSync(join(childAiDir, 'commands')),
            hasSkills: existsSync(join(childAiDir, 'skills')),
            isRoot: false,
            name: entry.name,
        });
    }
    return contexts;
}
export function readContextFile(context) {
    return readFileSync(context.contextFile, 'utf8');
}
