import '../../domain/entities/stream_event.dart';

class StreamEventModel {
  final String type;
  final Map<String, dynamic> data;

  const StreamEventModel({
    required this.type,
    required this.data,
  });

  factory StreamEventModel.fromJson(Map<String, dynamic> json) {
    final type = json['type'] as String? ??
        json['event'] as String? ??
        'text';

    // The data payload may be nested under 'data' or at the top level
    final data = json['data'] as Map<String, dynamic>? ?? json;

    return StreamEventModel(type: type, data: data);
  }

  /// Converts this model to a domain [StreamEvent].
  StreamEvent toEntity() {
    switch (type.toLowerCase()) {
      case 'thinking':
        return ThinkingEvent(
          data['content'] as String? ?? data['text'] as String? ?? '',
        );

      case 'text':
      case 'message':
      case 'stream_event':
        return TextEvent(
          data['content'] as String? ?? data['text'] as String? ?? '',
        );

      case 'tool_use':
      case 'tool_call':
        return ToolUseEvent(
          data['toolName'] as String? ?? data['tool_name'] as String? ?? data['name'] as String? ?? '',
          data['input'] as Map<String, dynamic>? ?? {},
        );

      case 'tool_result':
        return ToolResultEvent(
          data['toolName'] as String? ?? data['tool_name'] as String? ?? '',
          data['output'] as String? ?? data['content'] as String? ?? '',
          data['isError'] as bool? ?? data['is_error'] as bool? ?? false,
        );

      case 'approval_required':
      case 'approval':
        return ApprovalRequiredEvent(
          data['taskId'] as String? ?? data['task_id'] as String? ?? '',
          data['command'] as String? ?? '',
          data['riskLevel'] as int? ?? data['risk_level'] as int? ?? 0,
        );

      case 'completed':
      case 'done':
      case 'stream_end':
        return CompletedEvent(
          data['summary'] as String? ?? data['content'] as String? ?? '',
        );

      case 'error':
        return ErrorEvent(
          data['message'] as String? ?? data['error'] as String? ?? '未知错误',
        );

      case 'standing_order_draft':
        return StandingOrderDraftEvent(
          data['draft'] as Map<String, dynamic>? ?? data,
        );

      case 'standing_order_confirmed':
        return StandingOrderConfirmedEvent(
          data['orderId'] as String? ?? data['order_id'] as String? ?? '',
          data['orderName'] as String? ?? data['order_name'] as String? ?? '',
        );

      case 'task_info':
        return TaskInfoEvent(
          data['taskId'] as String? ?? data['task_id'] as String? ?? '',
        );

      case 'cancelled':
        return CancelledEvent();

      default:
        // Fall back to text event for unknown types
        return TextEvent(
          data['content'] as String? ?? data['text'] as String? ?? '',
        );
    }
  }
}
