import { buildContextSnapshot } from './context-snapshot.js';
/**
 * Merge two sessions of the same project.
 * - activeSpecs: union (no duplicate specId)
 * - decisions: union (no duplicate by timestamp+decision)
 * - modifiedFiles: union by path, most recent action wins
 * - toolCallCount: sum
 * - contextSummary: regenerated
 * The returned session uses the earlier startedAt and the later lastSavedAt.
 */
export function mergeSessions(a, b) {
    // Determine chronological order
    const first = a.startedAt <= b.startedAt ? a : b;
    const second = a.startedAt <= b.startedAt ? b : a;
    // Merge activeSpecs (union by specId, second wins on conflict)
    const specMap = new Map(first.activeSpecs.map((s) => [s.specId, s]));
    for (const s of second.activeSpecs) {
        specMap.set(s.specId, s);
    }
    const activeSpecs = [...specMap.values()];
    // Merge decisions (union by timestamp+decision key)
    const decisionKeys = new Set();
    const allDecisions = [...first.decisions, ...second.decisions];
    const decisions = allDecisions.filter((d) => {
        const key = `${d.timestamp}|${d.decision}`;
        if (decisionKeys.has(key)) {
            return false;
        }
        decisionKeys.add(key);
        return true;
    });
    // Merge modifiedFiles (union by path, later session's action wins)
    const fileMap = new Map(first.modifiedFiles.map((f) => [f.path, f]));
    for (const f of second.modifiedFiles) {
        fileMap.set(f.path, f);
    }
    const modifiedFiles = [...fileMap.values()];
    // Merge metadata (shallow merge, second wins on conflict)
    const metadata = { ...first.metadata, ...second.metadata };
    const merged = {
        id: first.id,
        projectId: first.projectId,
        startedAt: first.startedAt,
        lastSavedAt: second.lastSavedAt > first.lastSavedAt ? second.lastSavedAt : first.lastSavedAt,
        activeSpecs,
        decisions,
        modifiedFiles,
        contextSummary: '',
        toolCallCount: first.toolCallCount + second.toolCallCount,
        metadata,
    };
    merged.contextSummary = buildContextSnapshot(merged);
    return merged;
}
//# sourceMappingURL=session-merge.js.map