import Foundation

/// Handles streaming tool execution results.
///
/// This handler processes incremental content from tools like write_lyrics that stream
/// their output. It appends content chunks to the message containing the tool call.
/// An empty content string signals tool execution completion, which clears the
/// accumulatingToolCall field.
public struct ToolCallContentHandler: OrpheusEventHandler {
    public init() {}
    
    public func handle(
        event: OrpheusRealtimeEvent,
        session: OrpheusSession
    ) -> EventHandlerResult {
        guard case .toolCallContent(let toolCallId, let toolCallName, let content) = event else {
            return .noOp
        }
        
        print("📡 Received tool call content: \(toolCallName ?? "nil"), toolCallId=\(toolCallId)")
        
        var messagesList = session.messages
        guard let messageIndex = messagesList.firstIndex(where: { $0.accumulatingToolCall?.id == toolCallId }) else {
            print("⚠️ Message not found for tool call ID: \(toolCallId)")
            return .noOp
        }
        
        let message = messagesList[messageIndex]
        if content.isEmpty {
            // Empty content signals completion - clear accumulating tool call
            messagesList[messageIndex] = message.copy(
                accumulatingToolCall: nil,
                isStreaming: false
            )
        } else {
            // Append content
            messagesList[messageIndex] = message.copy(
                content: message.content + content
            )
        }
        
        print("📡 Updated message \(message.id) for tool call \(toolCallId)")
        return .messagesUpdated(messagesList)
    }
}

