/**
 * Behavioral Rules Engine — initialization and hook registration.
 */

import { logForDebugging } from '../../utils/debug.js'
import {
  registerPostSamplingHook,
  type REPLHookContext,
} from '../../utils/hooks/postSamplingHooks.js'
import { extractBehaviorRules } from './extractor.js'
import { formatRulesForPrompt } from './rules.js'

const SYSTEM_CONTEXT_KEY = 'behaviorRules'

/**
 * PostSamplingHook that extracts behavioral rules from user corrections
 * and injects active rules into the system context.
 */
async function behaviorRulesHook(context: REPLHookContext): Promise<void> {
  const { messages, systemContext } = context

  // Extract new rules from user corrections/confirmations
  try {
    await extractBehaviorRules(messages)
  } catch (err) {
    logForDebugging(`Behavior rule extraction failed: ${err}`)
  }

  // Inject active rules into system context
  try {
    const rulesPrompt = await formatRulesForPrompt()
    if (rulesPrompt) {
      systemContext[SYSTEM_CONTEXT_KEY] = rulesPrompt
    } else {
      delete systemContext[SYSTEM_CONTEXT_KEY]
    }
  } catch (err) {
    logForDebugging(`Behavior rules injection failed: ${err}`)
  }
}

/**
 * Initialize the behavioral rules engine.
 */
export function initBehaviorRules(): void {
  registerPostSamplingHook(behaviorRulesHook)
  logForDebugging('Behavioral rules engine initialized')
}

// Re-export for external use
export { loadRules, addRule, deleteRule, getTopRules } from './rules.js'
export type { BehaviorRule, BehaviorRulesState } from './types.js'
