// tools/sync-spec-to-code.ts — sync_spec_to_code handler
import { specStore, syncLogStore } from '../storage/index.js';
import { generateTodoComments, detectConflicts, buildSpecToCodeResult, parseAnnotationsFromProject, } from '../engine/living-spec/index.js';
import { extractCriteria } from '../engine/validator/extractors.js';
export async function handleSyncSpecToCode(args) {
    const { projectId, specId, projectPath } = args;
    // 1. Load spec
    const spec = await specStore.getSpec(projectId, specId);
    if (!spec) {
        return {
            content: [
                {
                    type: 'text',
                    text: JSON.stringify({ message: `Spec ${specId} not found` }, null, 2),
                },
            ],
            isError: true,
        };
    }
    // 2. Extract criteria
    const criteriaList = await extractCriteria(spec);
    const pendingCriteria = criteriaList.map((desc, i) => ({
        specId,
        criterion: i + 1,
        description: desc,
        status: 'pending',
    }));
    // 3. Parse existing annotations
    const parseResult = await parseAnnotationsFromProject(projectPath, specId);
    // 4. Generate TODOs for pending criteria
    const defaultFile = `${projectPath}/TODO-${specId}.md`;
    const todos = generateTodoComments(pendingCriteria, parseResult.annotations, defaultFile);
    // 5. Detect conflicts
    const statusMap = new Map();
    for (const criterion of pendingCriteria) {
        statusMap.set(`${specId}:AC-${criterion.criterion}`, criterion.status);
    }
    const conflicts = detectConflicts(parseResult.annotations, statusMap, 'spec-to-code');
    // 6. Build result
    const result = buildSpecToCodeResult(specId, todos, conflicts);
    // 7. Persist sync log and conflicts
    await syncLogStore.appendSyncLog(projectId, result.logEntries);
    if (conflicts.length > 0) {
        await syncLogStore.addConflicts(projectId, conflicts);
    }
    return {
        content: [
            {
                type: 'text',
                text: JSON.stringify({
                    ...result,
                    message: `Spec-to-code sync: ${todos.length} TODO(s) generated, ${conflicts.length} conflict(s) detected`,
                }, null, 2),
            },
        ],
    };
}
//# sourceMappingURL=sync-spec-to-code.js.map