import 'package:flutter_test/flutter_test.dart';
import '../lib/core/services/vector_service.dart';
import '../lib/core/services/rag_ai_service.dart';
import '../lib/core/services/rag_service.dart' show TutorMode;
import '../lib/core/models/content_chunk.dart';

void main() {
  group('AI Tutor RAG Services Tests', () {
    setUpAll(() async {
      // Setup test data
      print('🧪 Setting up test environment...');
    });

    test('VectorService - Generate Embedding', () async {
      print('🔍 Testing VectorService embedding generation...');

      const testText =
          'A fotossíntese é o processo pelo qual as plantas convertem luz solar em energia química.';

      final embedding = VectorService.generateEmbedding(testText);

      // Verify embedding properties
      expect(embedding.length, equals(384)); // Standard embedding size
      expect(
        embedding.every((x) => x >= -1.0 && x <= 1.0),
        isTrue,
      ); // Normalized

      print(
        '✅ Embedding generated successfully: ${embedding.length} dimensions',
      );
    });

    test('VectorService - Cosine Similarity', () {
      print('🔍 Testing cosine similarity calculation...');

      const text1 = 'A fotossíntese é importante para as plantas.';
      const text2 = 'As plantas usam fotossíntese para produzir energia.';
      const text3 = 'Os animais precisam de comida para sobreviver.';

      final embedding1 = VectorService.generateEmbedding(text1);
      final embedding2 = VectorService.generateEmbedding(text2);
      final embedding3 = VectorService.generateEmbedding(text3);

      final similarity12 = VectorService.cosineSimilarity(
        embedding1,
        embedding2,
      );
      final similarity13 = VectorService.cosineSimilarity(
        embedding1,
        embedding3,
      );

      // Similar texts should have higher similarity
      expect(similarity12, greaterThan(similarity13));
      expect(similarity12, greaterThan(0.5)); // Should be reasonably similar
      expect(similarity13, lessThan(0.3)); // Should be less similar

      print('✅ Cosine similarity working correctly');
      print('   Similar (fotossíntese): ${similarity12.toStringAsFixed(3)}');
      print(
        '   Different (plantas vs animais): ${similarity13.toStringAsFixed(3)}',
      );
    });

    test('RAGAIService - Service Availability', () async {
      print('🔍 Testing Ollama service availability...');

      try {
        final isAvailable = await RAGAIService.isServiceAvailable();

        if (isAvailable) {
          print('✅ Ollama service is available');

          // Test model info
          final modelInfo = await RAGAIService.getModelInfo();
          if (modelInfo != null) {
            print('   Model: ${modelInfo['name']}');
            print('   Size: ${modelInfo['size']}');
            print('   Modified: ${modelInfo['modified']}');
          }

          // Test simple query
          final testResponse = await RAGAIService.testService();
          print('   Test response: "$testResponse"');
        } else {
          print('⚠️  Ollama service is not available');
          print('   This is expected if the service is not running');
        }
      } catch (e) {
        print('❌ Error testing service availability: $e');
      }
    });

    test('RAG Pipeline - End-to-End Simulation', () async {
      print('🔍 Testing complete RAG pipeline simulation...');

      try {
        const userQuery = 'O que é fotossíntese?';
        const mode = TutorMode.explanation;

        // Step 1: Generate query embedding
        final queryEmbedding = VectorService.generateEmbedding(userQuery);
        print('   ✅ Query embedding generated');

        // Step 2: Simulate content retrieval (mock data)
        final mockChunks = [
          ContentChunk(
            id: 'chunk1',
            contentId: 'content1',
            text:
                'A fotossíntese é o processo pelo qual as plantas, algas e algumas bactérias convertem luz solar em energia química.',
            subject: 'Biologia',
            concept: 'Fotossíntese',
            unit: 'Processos Biológicos',
            difficulty: 0.6,
            grade: 10,
            embedding: VectorService.generateEmbedding(
              'fotossíntese plantas energia',
            ),
            sourceDocument: 'Biologia Manual.pdf',
            metadata: {'page': 45},
            createdAt: DateTime.now(),
          ),
        ];

        // Step 3: Test AI service if available
        try {
          final ragResponse = await RAGAIService.generateRAGResponse(
            userQuery: userQuery,
            context: userQuery,
            mode: mode,
            sources: mockChunks,
          );

          print('   ✅ RAG response generated');
          print('   Answer: "${ragResponse.answer.substring(0, 100)}..."');
          print('   Confidence: ${ragResponse.confidence.toStringAsFixed(2)}');
          print('   Sources: ${ragResponse.sources.length}');
        } catch (e) {
          print('   ⚠️  AI service not available: $e');
        }

        print('✅ RAG pipeline simulation completed successfully');
      } catch (e) {
        print('❌ Error in RAG pipeline: $e');
      }
    });

    tearDownAll(() async {
      print('🧹 Cleaning up test environment...');
    });
  });
}
