/**
 * Wander Detector — PostSamplingHook registration and integration.
 *
 * Registers a hook that runs after each model turn, analyzes for wander signals,
 * and injects course-correction into the system context for the next turn.
 */

import { logForDebugging } from '../../utils/debug.js'
import {
  registerPostSamplingHook,
  type REPLHookContext,
} from '../../utils/hooks/postSamplingHooks.js'
import { analyzeForWander, getWanderState } from './detector.js'

const SYSTEM_CONTEXT_KEY = 'wanderDetector'
const TURN_BUDGET_KEY = 'turnBudget'

/**
 * The wander detection PostSamplingHook.
 *
 * After each model turn:
 * 1. Analyzes message history for wander signals
 * 2. Injects a system context message if escalation is needed
 * 3. Updates the turn budget display
 */
async function wanderDetectorHook(context: REPLHookContext): Promise<void> {
  const { messages, systemContext } = context

  // Run wander analysis
  const escalation = analyzeForWander(messages)

  // Always update turn budget in system context
  const state = getWanderState()
  const approaches =
    state.approachesTried.length > 0
      ? state.approachesTried.join(', ')
      : 'none yet'
  systemContext[TURN_BUDGET_KEY] =
    `[Turn ${state.turnCount} | Approaches: ${approaches}]`

  if (escalation) {
    logForDebugging(
      `Wander detector: ${escalation.level} escalation (score: ${state.score})`,
    )

    switch (escalation.level) {
      case 'nudge':
        // Inject a course-correction hint into the system context
        systemContext[SYSTEM_CONTEXT_KEY] = [
          '<wander-detection>',
          escalation.message,
          '</wander-detection>',
        ].join('\n')
        break

      case 'compact':
        // Inject a stronger warning — the query loop's auto-compact will handle the rest
        systemContext[SYSTEM_CONTEXT_KEY] = [
          '<wander-detection level="compact">',
          escalation.message,
          'IMPORTANT: Stop the current approach entirely. Summarize what has been tried and what failed.',
          'Then choose a fundamentally different strategy.',
          '</wander-detection>',
        ].join('\n')
        break

      case 'halt':
        // Inject a halt message — tell the model to stop and ask the user
        systemContext[SYSTEM_CONTEXT_KEY] = [
          '<wander-detection level="halt">',
          escalation.message,
          'STOP. Do not attempt any more tool calls. Report to the user what you have tried',
          'and ask for guidance on a different approach.',
          '</wander-detection>',
        ].join('\n')
        break
    }
  } else {
    // Clear any previous wander detection message if the agent has recovered
    delete systemContext[SYSTEM_CONTEXT_KEY]
  }
}

/**
 * Initialize the wander detector.
 * Call this once during app startup to register the PostSamplingHook.
 */
export function initWanderDetector(): void {
  registerPostSamplingHook(wanderDetectorHook)
  logForDebugging('Wander detector initialized')
}

// Re-export for external access
export { getWanderState, resetWanderState } from './detector.js'
