// tools/sync-code-to-spec.ts — sync_code_to_spec handler
import { specStore, syncLogStore } from '../storage/index.js';
import { generateProgressUpdates, detectConflicts, buildCodeToSpecResult, parseAnnotationsFromProject, } from '../engine/living-spec/index.js';
import { extractCriteria } from '../engine/validator/extractors.js';
import { compactResult, formatKeyValue } from './output-formatter.js';
export async function handleSyncCodeToSpec(args) {
    const { projectId, specId, projectPath } = args;
    // 1. Load spec
    const spec = await specStore.getSpec(projectId, specId);
    if (!spec) {
        return {
            content: [{ type: 'text', text: `Spec ${specId} not found` }],
            isError: true,
        };
    }
    // 2. Parse annotations from code
    const parseResult = await parseAnnotationsFromProject(projectPath, specId);
    // 3. Build criteria status map (default: pending)
    const criteriaList = await extractCriteria(spec);
    const statusMap = new Map();
    for (let i = 0; i < criteriaList.length; i++) {
        statusMap.set(`${specId}:AC-${i + 1}`, 'pending');
    }
    // 4. Generate progress updates
    const updates = generateProgressUpdates(parseResult.annotations, statusMap);
    // 5. Detect conflicts
    const conflicts = detectConflicts(parseResult.annotations, statusMap, 'code-to-spec');
    // 6. Build result
    const result = buildCodeToSpecResult(specId, updates, conflicts);
    // 7. Persist
    await syncLogStore.appendSyncLog(projectId, result.logEntries);
    if (conflicts.length > 0) {
        await syncLogStore.addConflicts(projectId, conflicts);
    }
    return compactResult(formatKeyValue({
        specId,
        updatesCount: updates.length,
        conflictsCount: conflicts.length,
        message: `Code-to-spec sync: ${updates.length} progress update(s), ${conflicts.length} conflict(s)`,
    }));
}
//# sourceMappingURL=sync-code-to-spec.js.map