import Foundation

/// Handles message completion events.
///
/// This handler is called when the assistant finishes generating a message. It clears
/// all accumulating tool call data from messages, marking them as complete.
/// Matches Android's simple approach: just clear the tool call and mark as not streaming.
public struct MessageFinishedHandler: OrpheusEventHandler {
    public init() {}
    
    public func handle(
        event: OrpheusRealtimeEvent,
        session: OrpheusSession
    ) -> EventHandlerResult {
        guard case .messageFinished(let finishedMessageId, _) = event else {
            return .noOp
        }
        
        print("📝 Processing MessageFinished for messageId: \(finishedMessageId)")
        
        // Match Android: just clear accumulatingToolCall and set isStreaming to false
        // The content should already be in message.content from MessageToolCallHandler
        guard let messageIndex = session.messages.firstIndex(where: { $0.id == finishedMessageId }) else {
            print("⚠️ Message not found for MessageFinished: \(finishedMessageId)")
            return .noOp
        }
        
        let message = session.messages[messageIndex]
        return .updateMessage(
            messageId: finishedMessageId,
            transform: { _ in
                message.copy(
                    accumulatingToolCall: nil,
                    isStreaming: false
                )
            },
            clipIdsToFetch: nil
        )
    }
}

