import * as sessionStore from '../../storage/session-store.js';
import { randomUUID } from 'node:crypto';
import { buildContextSnapshot } from './context-snapshot.js';
import { updateCrossConversationMemory } from './memory-sync.js';
// --- module state ---
let currentSession = null;
let lastSaveTimestamp = 0;
const DEBOUNCE_MS = 30_000; // 30 seconds
// --- public API ---
/** Get the current in-memory session (may be null if none started). */
export function getCurrentSession() {
    return currentSession;
}
/** Reset module state (for testing). */
export function resetSessionState() {
    currentSession = null;
    lastSaveTimestamp = 0;
}
/** Start or resume a session for a project. */
export function startSession(projectId, existingSession) {
    if (existingSession) {
        currentSession = { ...existingSession };
        return currentSession;
    }
    const now = new Date().toISOString();
    currentSession = {
        id: randomUUID(),
        projectId,
        startedAt: now,
        lastSavedAt: now,
        activeSpecs: [],
        decisions: [],
        modifiedFiles: [],
        contextSummary: '',
        toolCallCount: 0,
        metadata: {},
    };
    return currentSession;
}
/** Record a tool call and maybe persist (debounce). */
export async function onToolCall(projectId) {
    if (!currentSession) {
        startSession(projectId);
    }
    if (currentSession) {
        currentSession.toolCallCount++;
        const now = Date.now();
        if (now - lastSaveTimestamp >= DEBOUNCE_MS) {
            await persistCurrentSession();
            lastSaveTimestamp = now;
        }
    }
}
/** Add an active spec to the current session. */
export function addActiveSpec(spec) {
    if (!currentSession) {
        return;
    }
    const exists = currentSession.activeSpecs.some((s) => s.specId === spec.specId);
    if (!exists) {
        currentSession.activeSpecs.push(spec);
    }
}
/** Add a decision to the current session. */
export function addDecision(decision) {
    if (!currentSession) {
        return;
    }
    currentSession.decisions.push(decision);
}
/** Add a modified file to the current session. */
export function addModifiedFile(file) {
    if (!currentSession) {
        return;
    }
    const idx = currentSession.modifiedFiles.findIndex((f) => f.path === file.path);
    if (idx >= 0) {
        currentSession.modifiedFiles[idx] = file;
    }
    else {
        currentSession.modifiedFiles.push(file);
    }
}
/** Force-save the current session to disk (bypasses debounce). */
export async function persistCurrentSession() {
    if (!currentSession) {
        return;
    }
    currentSession.lastSavedAt = new Date().toISOString();
    currentSession.contextSummary = buildContextSnapshot(currentSession);
    await sessionStore.save(currentSession);
    await updateCrossConversationMemory(currentSession);
    // Fire-and-forget cleanup
    void sessionStore.cleanup(currentSession.projectId).catch((err) => {
        console.error('[planu] session cleanup failed:', err);
    });
}
//# sourceMappingURL=auto-save.js.map