/**
 * Memory Phase Processor
 * Handles memory operations from LLM responses
 * Phase 2 of iteration: REASON -> MEMORY -> ACT
 */

import type { LLMIterationResponse } from '../reasoning/types'
import type { MemoryManager } from './manager'
import type { AgentScopedLogger } from '../observability/logging'
import { validateMemoryKeyOwnership } from './utils'

/**
 * Process memory operations from LLM response
 * Applies agent-directed memory management (set/delete)
 *
 * @param memoryManager - Memory manager instance
 * @param response - LLM iteration response with optional memoryOps
 * @param logger - Scoped logger for memory operations
 * @param iteration - Current iteration number
 */
export async function processMemory(
  memoryManager: MemoryManager,
  response: LLMIterationResponse,
  logger: AgentScopedLogger,
  iteration: number
): Promise<void> {
  if (!response.memoryOps) return

  const { memoryOps } = response

  // Apply set operations with domain validation
  if (memoryOps.set) {
    for (const [key, content] of Object.entries(memoryOps.set)) {
      // Validate ownership - skip if system-managed
      if (!validateMemoryKeyOwnership(key, logger, iteration)) {
        continue
      }

      const startTime = Date.now()
      // Auto-stringify non-string values (arrays, objects, etc.)
      const stringValue = typeof content === 'string' ? content : JSON.stringify(content)
      memoryManager.set(key, stringValue)
      const endTime = Date.now()
      logger.action('memory-set', `Set: ${key}`, iteration, startTime, endTime, endTime - startTime)
    }
  }

  // Apply delete operations with domain validation
  if (memoryOps.delete) {
    for (const key of memoryOps.delete) {
      // Validate ownership - skip if system-managed
      if (!validateMemoryKeyOwnership(key, logger, iteration)) {
        continue
      }

      const startTime = Date.now()
      const deleted = memoryManager.delete(key)
      const endTime = Date.now()
      if (deleted) {
        logger.action('memory-delete', `Deleted: ${key}`, iteration, startTime, endTime, endTime - startTime)
      } else {
        logger.action('memory-delete-missing', `Attempted to delete non-existent key: ${key}`, iteration, startTime, endTime, endTime - startTime)
      }
    }
  }
}
