import { generateRules, detectAgentPlatformFromFiles } from '../../engine/skill-generator.js';
import { knowledgeStore } from '../../storage/index.js';
import { writeFile, access, mkdir } from 'node:fs/promises';
import { join, dirname } from 'node:path';
import { assertEnglishOnlyArtifactText } from '../../engine/spec-language/english-only.js';
/**
 * Detect agent platform, generate rules, and write them to disk.
 * Only writes files that don't exist yet — never overwrites user custom rules.
 */
export async function runRulesWriter(projectPath, projectId, knowledge, recommendedSkills) {
    // Auto-detect AI platform and generate rules with skills
    const agentDetection = await detectAgentPlatformFromFiles(projectPath);
    const platform = agentDetection.platform;
    const constitution = await knowledgeStore.getConstitution(projectId);
    const generatedRules = await generateRules(platform, knowledge, constitution ?? undefined, {
        recommendedSkills,
    });
    // Auto-write rules file to disk (only if it doesn't exist — never overwrite user's custom rules)
    const rulesFilePath = join(projectPath, generatedRules.rulesFile.path);
    let rulesWritten = false;
    try {
        await access(rulesFilePath);
    }
    catch {
        await mkdir(dirname(rulesFilePath), { recursive: true });
        assertEnglishOnlyArtifactText(generatedRules.rulesFile.content, 'rule');
        await writeFile(rulesFilePath, generatedRules.rulesFile.content, 'utf-8');
        rulesWritten = true;
    }
    // Auto-write additional rules files (e.g., sdd-workflow.md skill)
    const additionalFilesWritten = [];
    for (const file of generatedRules.additionalFiles) {
        const filePath = join(projectPath, file.path);
        try {
            await access(filePath);
        }
        catch {
            await mkdir(dirname(filePath), { recursive: true });
            assertEnglishOnlyArtifactText(file.content, file.path.includes('skill') ? 'skill' : 'rule');
            await writeFile(filePath, file.content, 'utf-8');
            additionalFilesWritten.push(file.path);
        }
    }
    return { platform, generatedRules, rulesWritten, additionalFilesWritten };
}
//# sourceMappingURL=rules-writer.js.map