// engine/skill-generation/multi-agent-writer.ts — SPEC-607
// Detects which AI agents are present in a project and writes adapted skill files.
import { access, mkdir, writeFile, readFile } from 'node:fs/promises';
import { join, dirname } from 'node:path';
import { assertEnglishOnlyArtifactText } from '../spec-language/english-only.js';
import { adaptSkillForAgent } from './multi-agent-adapter.js';
// ---------------------------------------------------------------------------
// Agent detection signals
// ---------------------------------------------------------------------------
/** Files/directories that signal each agent's presence. */
const AGENT_DETECTION = {
    claude: '.claude', // always include claude
    cursor: '.cursor',
    copilot: '.github',
    gemini: 'GEMINI.md',
};
/** Output paths for each agent target. */
function resolveOutputPath(projectPath, metadata, target) {
    const slug = metadata.name.toLowerCase().replace(/[^a-z0-9-]/g, '-');
    switch (target) {
        case 'claude':
            return join(projectPath, '.claude', 'skills', `${slug}.md`);
        case 'cursor':
            return join(projectPath, '.cursor', 'rules', `${slug}.mdc`);
        case 'copilot':
            return join(projectPath, '.github', 'copilot-instructions.md');
        case 'gemini':
            return join(projectPath, 'GEMINI.md');
        default: {
            const _exhaustive = target;
            return _exhaustive;
        }
    }
}
async function isPresent(path) {
    try {
        await access(path);
        return true;
    }
    catch {
        return false;
    }
}
/** Detect which agent targets are present in the project. */
async function detectPresentAgents(projectPath) {
    const allTargets = ['claude', 'cursor', 'copilot', 'gemini'];
    const checks = await Promise.all(allTargets.map(async (target) => {
        const signal = AGENT_DETECTION[target];
        const present = await isPresent(join(projectPath, signal));
        // Claude is always included (even if .claude/ doesn't exist yet)
        return present || target === 'claude';
    }));
    return allTargets.filter((_, i) => checks[i]);
}
/** Write adapted content for copilot/gemini (append mode). */
async function writeAppendFile(filePath, content) {
    let existing = '';
    let created = false;
    try {
        existing = await readFile(filePath, 'utf-8');
    }
    catch {
        created = true;
    }
    const newContent = existing ? existing + '\n' + content : content;
    await mkdir(dirname(filePath), { recursive: true });
    await writeFile(filePath, newContent, 'utf-8');
    return created;
}
/** Write a new skill file (create/overwrite mode). */
async function writeNewFile(filePath, content) {
    let exists = false;
    try {
        await access(filePath);
        exists = true;
    }
    catch {
        /* file doesn't exist */
    }
    await mkdir(dirname(filePath), { recursive: true });
    await writeFile(filePath, content, 'utf-8');
    return !exists;
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
 * Write skill content to all detected (or specified) AI agent targets.
 *
 * @param skillContent - Agent Skills spec SKILL.md content (with frontmatter)
 * @param metadata - Parsed metadata for the skill
 * @param projectPath - Absolute path to the project root
 * @param targets - Optional explicit list of targets (default: auto-detect)
 */
export async function writeSkillToAllAgents(skillContent, metadata, projectPath, targets) {
    assertEnglishOnlyArtifactText(`${metadata.name}\n\n${metadata.description}\n\n${skillContent}`, 'skill');
    const resolvedTargets = targets ?? (await detectPresentAgents(projectPath));
    const results = [];
    await Promise.all(resolvedTargets.map(async (target) => {
        const adapted = adaptSkillForAgent(skillContent, metadata, target);
        const filePath = resolveOutputPath(projectPath, metadata, target);
        let created;
        if (target === 'copilot' || target === 'gemini') {
            // Append to existing file
            created = await writeAppendFile(filePath, adapted);
        }
        else {
            // Create/overwrite dedicated skill file
            created = await writeNewFile(filePath, adapted);
        }
        results.push({ path: filePath, target, created });
    }));
    return results;
}
//# sourceMappingURL=multi-agent-writer.js.map