/**
 * Trust Engine — PostSamplingHook registration and permission integration.
 *
 * Tracks tool success/failure after each turn and provides the
 * shouldAutoApprove() function for the permission system.
 */

import { logForDebugging } from '../../utils/debug.js'
import { getCwd } from '../../utils/cwd.js'
import {
  registerPostSamplingHook,
  type REPLHookContext,
} from '../../utils/hooks/postSamplingHooks.js'
import { recordSuccess, recordFailure } from './engine.js'

/**
 * PostSamplingHook that tracks tool outcomes for trust scoring.
 * Inspects the most recent assistant turn's tool uses and their results.
 */
async function trustTrackingHook(context: REPLHookContext): Promise<void> {
  const { messages } = context
  const projectPath = getCwd()

  // Find the last assistant message and its tool results
  const recentMessages = messages.slice(-10) // Look at last 10 messages

  for (let i = 0; i < recentMessages.length; i++) {
    const msg = recentMessages[i]!
    if (msg.type !== 'assistant') continue

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const content = (msg as any).message?.content
    if (!Array.isArray(content)) continue

    const toolUses = content.filter(
      (b: { type: string }) => b.type === 'tool_use',
    )

    for (const toolUse of toolUses) {
      const toolName = toolUse.name as string
      const toolUseId = toolUse.id as string

      // Look for the corresponding tool result in subsequent user messages
      const resultMsg = recentMessages
        .slice(i + 1)
        .find((m) => {
          if (m.type !== 'user') return false
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          const userContent = (m as any).message?.content
          if (!Array.isArray(userContent)) return false
          return userContent.some(
            (b: { type: string; tool_use_id?: string }) =>
              b.type === 'tool_result' && b.tool_use_id === toolUseId,
          )
        })

      if (!resultMsg) continue

      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const userContent = (resultMsg as any).message?.content as Array<{
        type: string
        tool_use_id?: string
        is_error?: boolean
      }>

      const result = userContent?.find(
        (b) => b.type === 'tool_result' && b.tool_use_id === toolUseId,
      )

      if (result) {
        try {
          if (result.is_error) {
            await recordFailure(projectPath, toolName)
          } else {
            await recordSuccess(projectPath, toolName)
          }
        } catch (err) {
          logForDebugging(`Trust tracking error: ${err}`)
        }
      }
    }
  }
}

/**
 * Initialize the trust engine.
 */
export function initTrustEngine(): void {
  registerPostSamplingHook(trustTrackingHook)
  logForDebugging('Trust engine initialized')
}

// Re-export for external use
export {
  shouldAutoApprove,
  resetTrust,
  formatTrustStatus,
  getTrustProfile,
} from './engine.js'
