/**
 * Memory Domain Ownership
 * Defines which component owns each category of memory keys
 *
 * This prevents conflicts between LLM memory operations and tool/action side effects.
 * Each memory key has a clear owner: LLM, tool, or action.
 */

/**
 * Memory domains registry
 * Defines ownership boundaries for memory keys
 */
export const MEMORY_DOMAINS = {
  /**
   * Tool-owned keys
   * Updated automatically by tools as side effects
   * LLM cannot modify these via memoryOps
   *
   * Tools manage complex structured data (caches, indexes, etc.)
   * that would be error-prone for LLM to update via JSON strings.
   */
  TOOL_OWNED: [
    'notion-pages-cache', // Notion tools manage page hierarchy
    'github-repo-cache', // GitHub tools manage repository structure
    'slack-channel-cache', // Slack tools manage channel data
  ],

  /**
   * Action-owned keys
   * Updated by framework actions (navigate-knowledge, etc.)
   * LLM cannot modify these via memoryOps
   *
   * Actions manage framework state that controls execution flow.
   */
  ACTION_OWNED: [
    'knowledge-map-state', // navigate-knowledge action manages this
  ],

  /**
   * LLM-owned keys
   * All keys NOT in TOOL_OWNED or ACTION_OWNED
   * Managed via memoryOps by agent reasoning
   *
   * LLM manages semantic memory (business context, decisions, etc.)
   * that requires understanding and judgment.
   */
} as const

/**
 * Tool-owned memory key type
 */
type ToolOwnedKey = (typeof MEMORY_DOMAINS.TOOL_OWNED)[number]

/**
 * Action-owned memory key type
 */
type ActionOwnedKey = (typeof MEMORY_DOMAINS.ACTION_OWNED)[number]

/**
 * Check if a memory key is owned by tools
 *
 * @param key - Memory key to check
 * @returns true if key is tool-owned
 */
export function isToolOwnedKey(key: string): key is ToolOwnedKey {
  return (MEMORY_DOMAINS.TOOL_OWNED as readonly string[]).includes(key)
}

/**
 * Check if a memory key is owned by actions
 *
 * @param key - Memory key to check
 * @returns true if key is action-owned
 */
export function isActionOwnedKey(key: string): key is ActionOwnedKey {
  return (MEMORY_DOMAINS.ACTION_OWNED as readonly string[]).includes(key)
}

/**
 * Check if LLM can update this key via memoryOps
 *
 * @param key - Memory key to check
 * @returns true if key is LLM-owned (not tool or action owned)
 */
export function isLLMOwnedKey(key: string): boolean {
  return !isToolOwnedKey(key) && !isActionOwnedKey(key)
}

/**
 * Get the owner type for a memory key
 *
 * @param key - Memory key to check
 * @returns 'tool' | 'action' | 'llm'
 */
export function getKeyOwner(key: string): 'tool' | 'action' | 'llm' {
  if (isToolOwnedKey(key)) return 'tool'
  if (isActionOwnedKey(key)) return 'action'
  return 'llm'
}
