import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import '../utils/logger.dart';

/// Service for managing conversation history in Firestore
/// Structure: conversations/{conversationId}/messages/{messageId}
class ChatMemoryService {
  static final FirebaseFirestore _firestore = FirebaseFirestore.instance;
  static final FirebaseAuth _auth = FirebaseAuth.instance;

  /// Get or create a conversation for the current user
  static Future<String> _getOrCreateConversationId() async {
    final user = _auth.currentUser;
    if (user == null) {
      throw Exception('User not authenticated');
    }

    // For simplicity, use user's UID as conversation ID
    // In a multi-conversation system, this would create new conversation docs
    return user.uid;
  }

  /// Save a message to Firestore
  static Future<void> saveMessage({
    required String role, // 'user' or 'assistant'
    required String content,
  }) async {
    try {
      final conversationId = await _getOrCreateConversationId();
      final user = _auth.currentUser;
      
      if (user == null) return;

      final messageData = {
        'role': role,
        'content': content,
        'createdAt': FieldValue.serverTimestamp(),
        'userId': user.uid,
      };

      await _firestore
          .collection('conversations')
          .doc(conversationId)
          .collection('messages')
          .add(messageData);

      Logger.info('Message saved to Firestore: role=$role');
    } catch (e) {
      Logger.error('Error saving message: $e');
    }
  }

  /// Get the last N messages from conversation history
  /// Returns list of messages sorted by createdAt ascending (oldest first)
  static Future<List<Map<String, dynamic>>> getRecentMessages({
    int limit = 20,
  }) async {
    try {
      final conversationId = await _getOrCreateConversationId();

      final snapshot = await _firestore
          .collection('conversations')
          .doc(conversationId)
          .collection('messages')
          .orderBy('createdAt', descending: true)
          .limit(limit)
          .get();

      // Convert to list and reverse to get ascending order (oldest first)
      final messages = snapshot.docs
          .map((doc) => {
                'role': doc.data()['role'] as String,
                'content': doc.data()['content'] as String,
                'createdAt': doc.data()['createdAt'] as Timestamp?,
              })
          .toList()
          .reversed
          .toList();

      // Log de confirmação de ordem
      if (messages.isNotEmpty) {
        Logger.info('History order fixed. First message: ${messages.first['role']} - ${(messages.first['content'] as String).substring(0, (messages.first['content'] as String).length > 30 ? 30 : (messages.first['content'] as String).length)}...');
      }
      Logger.info('Retrieved ${messages.length} messages from history (oldest first)');
      return messages;
    } catch (e) {
      Logger.error('Error getting recent messages: $e');
      return [];
    }
  }

  /// Build messages array for API request
  /// Returns list of message maps with 'role' and 'content' keys
  static Future<List<Map<String, String>>> buildMessagesForAPI({
    required String currentUserMessage,
    int historyLimit = 20,
  }) async {
    final messages = <Map<String, String>>[];

    // 1. Get recent conversation history
    final history = await getRecentMessages(limit: historyLimit);

    // 2. Add historical messages
    for (final msg in history) {
      messages.add({
        'role': msg['role'] as String,
        'content': msg['content'] as String,
      });
    }

    // 3. Add current user message
    messages.add({
      'role': 'user',
      'content': currentUserMessage,
    });

    Logger.info('Built messages array with ${messages.length} messages for API');
    return messages;
  }

  /// Clear conversation history for current user
  static Future<void> clearHistory() async {
    try {
      final conversationId = await _getOrCreateConversationId();

      final snapshot = await _firestore
          .collection('conversations')
          .doc(conversationId)
          .collection('messages')
          .get();

      // Delete all messages in batches
      final batch = _firestore.batch();
      for (final doc in snapshot.docs) {
        batch.delete(doc.reference);
      }
      await batch.commit();

      Logger.info('Conversation history cleared');
    } catch (e) {
      Logger.error('Error clearing history: $e');
    }
  }
}
