/**
 * Google 直连聊天多轮 contents 记忆（进程内；不用于 TASK 热路径 dispatch prompt）。
 */

import { sanitizeGeminiContents } from "./geminiChatHistory.ts";

export type GeminiChatContent = { role: string; parts: unknown[] };

const DEFAULT_MAX_MESSAGES = 24;

export class GeminiChatMemory {
  private readonly store = new Map<string, GeminiChatContent[]>();

  static buildKey(sdkAgentId: string, agentId: string): string {
    return `${sdkAgentId}:${agentId}`;
  }

  load(key: string): GeminiChatContent[] {
    const stored = this.store.get(key);
    if (!stored?.length) return [];
    const cloned = stored.map((m) => ({
      role: m.role,
      parts: Array.isArray(m.parts) ? [...m.parts] : [],
    }));
    return sanitizeGeminiContents(cloned);
  }

  save(
    key: string,
    contents: readonly GeminiChatContent[],
    maxMessages = DEFAULT_MAX_MESSAGES,
  ): void {
    const cap = Math.max(2, maxMessages);
    const sanitized = sanitizeGeminiContents(contents);
    const trimmed =
      sanitized.length > cap
        ? sanitized.slice(sanitized.length - cap)
        : [...sanitized];
    const reSanitized = sanitizeGeminiContents(trimmed);
    this.store.set(
      key,
      reSanitized.map((m) => ({ role: m.role, parts: m.parts })),
    );
  }

  clear(key: string): void {
    this.store.delete(key);
  }
}
