import Foundation

/// Handles generate_song tool results.
///
/// This handler triggers clip fetching via the UpdateMessage event's clipIdsToFetch field.
/// The repository will fetch the clips asynchronously when applying this event.
public struct ToolCallResultHandler: OrpheusEventHandler {
    public init() {
        // No dependencies needed - clip fetching is handled in repository layer
    }
    
    public func handle(
        event: OrpheusRealtimeEvent,
        session: OrpheusSession
    ) -> EventHandlerResult {
        guard case .toolCallResult(let toolCallId, let toolCallName, let clipIds) = event else {
            return .noOp
        }
        
        print("📡 Received tool call result: \(toolCallName ?? "nil"), toolCallId=\(toolCallId), clipIds=\(clipIds)")
        
        let toolName = ToolName.fromValue(toolCallName)
        if toolName != .generateSong {
            print("📡 Ignoring tool call: \(toolCallName ?? "nil")")
            return .noOp
        }
        
        if clipIds.isEmpty {
            print("⚠️ Empty clip IDs for tool call: \(toolCallId)")
            return .noOp
        }
        
        // Find the message with this tool call
        guard let messageIndex = session.messages.firstIndex(where: { $0.accumulatingToolCall?.id == toolCallId }) else {
            print("⚠️ Message not found for tool call ID: \(toolCallId)")
            return .noOp
        }
        
        let message = session.messages[messageIndex]
        
        // Return update event with clipIdsToFetch
        // The repository will fetch the clips asynchronously
        return .updateMessage(
            messageId: message.id,
            transform: { msg in
                msg.copy(
                    contentType: .toolCallContent,
                    accumulatingToolCall: nil,
                    isStreaming: false
                )
            },
            clipIdsToFetch: clipIds
        )
    }
}

