import Foundation

/// Handles tool execution failures.
///
/// This handler is called when a tool (like generate_song or write_lyrics) fails during
/// execution. It updates the message with the error details and clears the accumulatingToolCall
/// field to indicate the tool execution is complete (though unsuccessful).
public struct ToolCallFailureHandler: OrpheusEventHandler {
    public init() {}
    
    public func handle(
        event: OrpheusRealtimeEvent,
        session: OrpheusSession
    ) -> EventHandlerResult {
        guard case .toolCallFailure(let toolCallId, let toolCallName, let errorMessage) = event else {
            return .noOp
        }
        
        print("⚠️ Tool call failed, tool call id: \(toolCallId), error: \(errorMessage)")
        
        var messagesList = session.messages
        guard let messageIndex = messagesList.firstIndex(where: { $0.accumulatingToolCall?.id == toolCallId }) else {
            print("⚠️ Message not found for failed tool call id: \(toolCallId)")
            return .noOp
        }
        
        let message = messagesList[messageIndex]
        messagesList[messageIndex] = message.copy(
            content: errorMessage,
            accumulatingToolCall: nil,
            isStreaming: false
        )
        
        print("📡 Updated message id: \(message.id) with error for tool call id: \(toolCallId)")
        return .messagesUpdated(messagesList)
    }
}

