// =============================================================================
// Pure memory API. The in-process agent-runner collects memory updates into an
// array on the ToolContext (ctx.memoryUpdates) so the supervisor loop can
// persist them at end-of-turn. MCP clients don't share that array, so the MCP
// server keeps its own module-level store keyed by an optional sessionKey.
// =============================================================================

export interface MemoryEntry {
    key: string;
    type: string; // "tech_stack" | "decision" | "feature" | "goal" | "constraint" | "note"
    value: string;
}

export interface MemoryInput {
    key: string;
    type: string;
    value: string;
}

export function toEntry(input: MemoryInput): MemoryEntry {
    return { key: input.key, type: input.type, value: input.value };
}

// -------------------------------------------------------------------
// In-memory store used by the MCP server path (the in-process path
// appends directly to ctx.memoryUpdates and ignores this store).
// -------------------------------------------------------------------

const memoryStore = new Map<string, MemoryEntry[]>();

export function saveMemoryToStore(sessionKey: string, input: MemoryInput): { saved: true; entry: MemoryEntry } {
    const entry = toEntry(input);
    const list = memoryStore.get(sessionKey) ?? [];
    list.push(entry);
    memoryStore.set(sessionKey, list);
    return { saved: true, entry };
}

export function listMemoryFromStore(sessionKey: string): MemoryEntry[] {
    return [...(memoryStore.get(sessionKey) ?? [])];
}

export function clearMemoryStore(sessionKey: string): void {
    memoryStore.delete(sessionKey);
}
