import { ti } from '../../i18n/index.js';
import { knowledgeStore } from '../../storage/index.js';
import { deriveAutoDetectedPrinciples, extractPrinciplesFromClaudeMd, detectConflicts, } from './principle-detector.js';
import { compactResult, formatKeyValue } from '../output-formatter.js';
export async function handleInitConstitution(params) {
    const { projectId, autoDetect = true, principles: manualPrinciples } = params;
    try {
        // Check if project exists
        const knowledge = await knowledgeStore.getKnowledge(projectId);
        if (!knowledge) {
            return {
                content: [{ type: 'text', text: ti('project.notFound', {}) }],
                isError: true,
            };
        }
        // Check for existing constitution
        const existingConstitution = await knowledgeStore.getConstitution(projectId);
        const allPrinciples = [];
        // Auto-detect principles from project knowledge
        if (autoDetect) {
            const autoPrinciples = deriveAutoDetectedPrinciples(knowledge);
            allPrinciples.push(...autoPrinciples);
            // Extract from CLAUDE.md / rules files
            const claudeMdPrinciples = await extractPrinciplesFromClaudeMd(knowledge.projectPath);
            allPrinciples.push(...claudeMdPrinciples);
        }
        // Add manual principles (override auto-detected with same ID)
        if (manualPrinciples && manualPrinciples.length > 0) {
            for (const manual of manualPrinciples) {
                const existingIdx = allPrinciples.findIndex((p) => p.id === manual.id);
                if (existingIdx !== -1) {
                    allPrinciples[existingIdx] = manual;
                }
                else {
                    allPrinciples.push(manual);
                }
            }
        }
        // Preserve immutable principles from existing constitution
        if (existingConstitution) {
            for (const existing of existingConstitution.principles) {
                if (existing.immutable) {
                    const inNew = allPrinciples.findIndex((p) => p.id === existing.id);
                    if (inNew !== -1) {
                        // Keep the immutable version
                        allPrinciples[inNew] = existing;
                    }
                    else {
                        allPrinciples.push(existing);
                    }
                }
            }
        }
        // Compute merge result (only when updating an existing constitution)
        let mergeResult = null;
        if (existingConstitution) {
            const existingIds = new Set(existingConstitution.principles.map((p) => p.id));
            const added = allPrinciples.filter((p) => !existingIds.has(p.id)).length;
            const preserved = allPrinciples.filter((p) => existingIds.has(p.id)).length;
            const conflicts = detectConflicts(existingConstitution.principles, allPrinciples);
            mergeResult = { added, preserved, conflicts };
        }
        const now = new Date().toISOString();
        const constitution = {
            projectId,
            principles: allPrinciples,
            createdAt: existingConstitution?.createdAt ?? now,
            updatedAt: now,
            version: existingConstitution ? existingConstitution.version + 1 : 1,
        };
        await knowledgeStore.saveConstitution(projectId, constitution);
        // Build summary by category
        const byCategory = {};
        for (const p of allPrinciples) {
            byCategory[p.category] = (byCategory[p.category] ?? 0) + 1;
        }
        const result = {
            projectId,
            version: constitution.version,
            isUpdate: !!existingConstitution,
            principlesCount: allPrinciples.length,
            byCategory,
            bySource: {
                'auto-detected': allPrinciples.filter((p) => p.source === 'auto-detected').length,
                'user-defined': allPrinciples.filter((p) => p.source === 'user-defined').length,
                'claude-md': allPrinciples.filter((p) => p.source === 'claude-md').length,
                learned: allPrinciples.filter((p) => p.source === 'learned').length,
            },
            immutableCount: allPrinciples.filter((p) => p.immutable).length,
            strictCount: allPrinciples.filter((p) => p.enforceLevel === 'strict').length,
            principles: allPrinciples,
            ...(mergeResult ? { mergeResult } : {}),
            message: ti('tools.init_constitution.success', {
                projectId,
                count: String(allPrinciples.length),
            }),
        };
        const bySourceStr = Object.entries(result.bySource)
            .map(([k, v]) => `${k}: ${v}`)
            .join(', ');
        const byCategoryStr = Object.entries(result.byCategory)
            .map(([k, v]) => `${k}: ${v}`)
            .join(', ');
        return compactResult(formatKeyValue({
            projectId: result.projectId,
            version: result.version,
            isUpdate: result.isUpdate,
            principlesCount: result.principlesCount,
            immutableCount: result.immutableCount,
            strictCount: result.strictCount,
            message: result.message,
        }, 'Constitution') +
            `\n\n**By Source**: ${bySourceStr}` +
            `\n**By Category**: ${byCategoryStr}` +
            (result.mergeResult
                ? `\n**Merge**: added ${result.mergeResult.added}, preserved ${result.mergeResult.preserved}, conflicts ${result.mergeResult.conflicts.length}`
                : '') +
            `\n\n**Principles** (${result.principles.length}):\n` +
            result.principles.map((p) => `- [${p.id}] ${p.principle} (${p.source})`).join('\n'));
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: ti('errors.internalError', { message }) }],
            isError: true,
        };
    }
}
//# sourceMappingURL=handler.js.map