// engine/skill-deployer.ts — SPEC-650: Deploy skills to client-specific locations
import { createHash } from 'node:crypto';
import { readFile, writeFile, mkdir, access } from 'node:fs/promises';
import { join } from 'node:path';
import { detectAndCacheClient } from './client-detection.js';
function contentHash(content) {
    return createHash('sha256').update(content).digest('hex').substring(0, 16);
}
async function fileHashMatches(filePath, content) {
    try {
        const existing = await readFile(filePath, 'utf-8');
        return contentHash(existing) === contentHash(content);
    }
    catch {
        return false;
    }
}
async function writeIfChanged(filePath, content) {
    if (await fileHashMatches(filePath, content)) {
        return false;
    }
    await mkdir(join(filePath, '..'), { recursive: true });
    await writeFile(filePath, content, 'utf-8');
    return true;
}
function cursorMdcContent(name, content) {
    return `---\ndescription: ${name} skill\nglobs: ["**/*"]\nalwaysApply: false\n---\n\n${content}`;
}
function resolveSkillPath(projectPath, name, client) {
    switch (client) {
        case 'claude-code':
            return join(projectPath, '.claude', 'skills', `${name}.md`);
        case 'cursor':
            return join(projectPath, '.cursor', 'rules', `${name}.mdc`);
        case 'codex':
            return join(projectPath, '.agents', 'skills', name, 'SKILL.md');
        case 'windsurf':
        case 'copilot':
        case 'gemini':
        case 'unknown':
            return join(projectPath, 'planu', 'skills', `${name}.md`);
    }
}
function prepareContent(name, content, client) {
    if (client === 'cursor') {
        return cursorMdcContent(name, content);
    }
    return content;
}
async function deploySingleSkill(projectPath, skill, client) {
    const filePath = resolveSkillPath(projectPath, skill.name, client);
    const finalContent = prepareContent(skill.name, skill.content, client);
    const written = await writeIfChanged(filePath, finalContent);
    return { name: skill.name, path: filePath, written };
}
/**
 * SPEC-650: Deploy skills to the location appropriate for the detected LLM client.
 * Idempotent — files are only overwritten if content hash changed.
 */
export async function deploySkills(projectPath, skills) {
    const detectedClient = await detectAndCacheClient(projectPath);
    const results = await Promise.all(skills.map((s) => deploySingleSkill(projectPath, s, detectedClient)));
    return { detectedClient, results };
}
/**
 * SPEC-650: Check whether skill file already exists for this client.
 */
export async function skillFileExists(projectPath, skillName, client) {
    const filePath = resolveSkillPath(projectPath, skillName, client);
    try {
        await access(filePath);
        return true;
    }
    catch {
        return false;
    }
}
//# sourceMappingURL=skill-deployer.js.map