// ============================================================================
// H33 Agent SDK — Memory checkpoint helpers
// ============================================================================

import { createHash } from 'crypto';

/**
 * Hash an arbitrary memory state for attestation. Accepts any serializable
 * value (context window, retrieved documents, agent scratchpad, etc.) and
 * returns a SHA-256 hex digest.
 *
 * @param state - The memory state to hash (any serializable value)
 * @returns SHA-256 hex string
 *
 * @example
 * ```ts
 * const hash = hashMemoryState({
 *   retrievedDocs: docs,
 *   scratchpad: notes,
 *   timestamp: Date.now(),
 * });
 * await session.checkpointMemory(hash, contextHash, sizeBytes);
 * ```
 */
export function hashMemoryState(state: unknown): string {
  const serialized = JSON.stringify(state);
  return createHash('sha256').update(serialized).digest('hex');
}

/**
 * Hash a context window (chat message array) for attestation. Messages are
 * serialized in order to produce a deterministic hash.
 *
 * @param messages - Array of chat messages with role and content
 * @returns SHA-256 hex string
 *
 * @example
 * ```ts
 * const hash = hashContextWindow([
 *   { role: 'system', content: 'You are a claims review agent.' },
 *   { role: 'user', content: 'Show me open claims for Q1.' },
 *   { role: 'assistant', content: 'Found 47 open claims...' },
 * ]);
 * ```
 */
export function hashContextWindow(
  messages: Array<{ role: string; content: string }>
): string {
  // Deterministic serialization: role + content pairs in order
  const canonical = messages
    .map((m) => `${m.role}:${m.content}`)
    .join('\n');
  return createHash('sha256').update(canonical).digest('hex');
}
