// tools/resolve-spec-conflict.ts — SPEC-172: Resolve merge conflicts between spec and code
// Presents a 3-way diff (original spec, new spec, code changes) and applies resolution policy.
import { resolveSpecConflict } from '../engine/living-spec/index.js';
import { jsonResult, errJson } from './response-helpers.js';
/**
 * Handle the resolve_spec_conflict tool call.
 * Detects conflicts from simultaneous spec + code changes and applies the resolution policy.
 */
export function handleResolveSpecConflict(args) {
    const { specId, originalSpec, newSpec, codeChanges, policy = 'always-ask' } = args;
    if (!specId.trim()) {
        return errJson({ error: 'specId is required and must not be empty.' });
    }
    if (!originalSpec.trim() && !newSpec.trim()) {
        return errJson({ error: 'At least one of originalSpec or newSpec must be non-empty.' });
    }
    const resolution = resolveSpecConflict(originalSpec, newSpec, codeChanges, specId, policy);
    const totalConflicts = resolution.autoResolved.length + resolution.pendingReview.length;
    const summary = {
        specId,
        policy,
        totalConflicts,
        autoResolved: resolution.autoResolved.length,
        pendingReview: resolution.pendingReview.length,
        resolvedAt: resolution.resolvedAt,
    };
    const output = {
        summary,
        autoResolved: resolution.autoResolved.map((r) => ({
            conflictId: r.conflict.id,
            category: r.conflict.category,
            description: r.conflict.description,
            winner: r.winner,
            policy: r.appliedPolicy,
            explanation: r.explanation,
        })),
        pendingReview: resolution.pendingReview.map((c) => ({
            conflictId: c.id,
            category: c.category,
            description: c.description,
            specSide: c.specSide,
            codeSide: c.codeSide,
        })),
        conflictMarkers: resolution.conflictMarkers.length > 0 ? resolution.conflictMarkers.join('\n') : null,
        message: buildMessage(resolution.autoResolved.length, resolution.pendingReview.length, policy),
    };
    return jsonResult(output);
}
function buildMessage(autoResolved, pendingReview, policy) {
    if (autoResolved === 0 && pendingReview === 0) {
        return 'No conflicts detected between spec and code changes.';
    }
    const parts = [];
    if (autoResolved > 0) {
        parts.push(`${String(autoResolved)} conflict(s) auto-resolved using "${policy}" policy.`);
    }
    if (pendingReview > 0) {
        parts.push(`${String(pendingReview)} conflict(s) require human review. ` +
            `Use the conflictMarkers field to see git-style conflict markers for your spec.md.`);
    }
    return parts.join(' ');
}
//# sourceMappingURL=resolve-spec-conflict.js.map