// engine/skill-bootstrap/skill-writer.ts — SPEC-439: Write skills to target AI tool files
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { join, dirname } from 'node:path';
import { assertEnglishOnlyArtifactText } from '../spec-language/english-only.js';
const AUTO_SECTION_HEADER = '## Auto-installed Skills (Planu)';
function targetToRelativePath(target) {
    switch (target) {
        case 'cursorrules':
            return '.cursorrules';
        case 'windsurfrules':
            return '.windsurfrules';
        case 'claude-md':
            return 'CLAUDE.md';
        case 'kiro-steering':
            return '.kiro/steering/planu-skills.md';
        case 'agents-md':
            return 'AGENTS.md';
        case 'clinerules':
            return '.clinerules';
        default: {
            const _exhaustive = target;
            return _exhaustive;
        }
    }
}
async function readFileSafe(filePath) {
    try {
        return await readFile(filePath, 'utf-8');
    }
    catch {
        return null;
    }
}
export function formatSkillsForTarget(skills, target) {
    if (target === 'cursorrules' || target === 'windsurfrules' || target === 'clinerules') {
        return skills.map((s) => s.content).join('\n\n');
    }
    // claude-md, agents-md, kiro-steering: add headers per skill source
    const parts = [];
    for (const skill of skills) {
        parts.push(`## Skills from ${skill.sourceName}\n\n${skill.content}`);
    }
    return parts.join('\n\n');
}
export async function writeSkillFile(projectPath, target, content, autoMerge) {
    assertEnglishOnlyArtifactText(content, 'skill');
    const relativePath = targetToRelativePath(target);
    const filePath = join(projectPath, relativePath);
    await mkdir(dirname(filePath), { recursive: true });
    if (autoMerge) {
        const existing = await readFileSafe(filePath);
        if (existing !== null) {
            // Remove any previously auto-installed section to avoid duplication
            const autoSectionIndex = existing.indexOf(AUTO_SECTION_HEADER);
            const base = autoSectionIndex >= 0 ? existing.slice(0, autoSectionIndex).trimEnd() : existing.trimEnd();
            const merged = `${base}\n\n${AUTO_SECTION_HEADER}\n${content}`;
            await writeFile(filePath, merged, 'utf-8');
            return filePath;
        }
    }
    await writeFile(filePath, content, 'utf-8');
    return filePath;
}
//# sourceMappingURL=skill-writer.js.map