import 'dart:convert';

// Contoh response dari crop.health API (disederhanakan)
final String cropHealthResponse = '''
{
  "result": {
    "disease": {
      "suggestions": [
        {
          "id": "081a574211a34cf3",
          "name": "sugarcane rust",
          "probability": 0.6615,
          "details": {
            "severity": "This plant disease is highly severe, causing significant losses in crop yield and quality. It primarily affects the leaf blades and sheaths and is most destructive during the elongation stage of crop growth.",
            "symptoms": {
              "Yellowing of leaves": " Sugarcane rust can also cause yellowing of leaves. This is typically more pronounced around the lesions.",
              "Appearance of lesions": " The initial signs of sugarcane rust disease usually begin with the appearance of reddish-brown pustules or lesions on both sides of the leaf blades."
            },
            "treatment": {
              "prevention": [
                "Clean Farm Equipment: Regularly clean and sterilize farm tools and equipment to prevent the spread of the disease.",
                "Opt for Disease-Free Planting Material: Always use disease-free planting material to prevent early disease introduction."
              ],
              "chemical treatment": [
                "Use Systemic fungicides: Apply systemic fungicides that can get absorbed by the plant and kill the fungus.",
                "Safeguard with Protective fungicides: Protect against spores by spraying protective fungicides on the plant."
              ]
            },
            "description": "Sugarcane rust disease is a prominent plant illness caused by the fungal pathogen Puccinia melanocephala. While this disease primarily affects sugarcane crops, other plant species within the Poaceae family can also serve as host plants."
          }
        },
        {
          "id": "0b2e2f8c90065723",
          "name": "brown spot of rice",
          "probability": 0.2646,
          "details": {
            "severity": "This plant disease is highly harmful, with severe cases causing up to 50% yield losses.",
            "symptoms": {
              "Reduced grain size": " One of the symptoms of the brown spot of rice disease is the noticeable reduction in the size of grains, due to the hindered growth of the plant."
            },
            "description": "Brown spot of rice, caused by the fungus Bipolaris oryzae, is a significant plant disease encountered worldwide."
          }
        }
      ]
    },
    "crop": {
      "suggestions": [
        {
          "name": "rice",
          "probability": 0.0022,
          "scientific_name": "Oryza sativa"
        }
      ]
    }
  }
}
''';

// Kamus terjemahan manual untuk field-field penting
final Map<String, String> cropNameTranslations = {
  'rice': 'Padi',
  'tomato': 'Tomat',
  'potato': 'Kentang',
  'corn': 'Jagung',
  'sugarcane': 'Tebu'
};

final Map<String, String> diseaseNameTranslations = {
  'brown spot of rice': 'Bercak Coklat Padi',
  'sugarcane rust': 'Karat Tebu',
  'bacterial blight of rice': 'Hawar Daun Bakteri Padi',
  'false smut': 'Noda Palsu',
  'Septoria nodorum blotch': 'Bercak Septoria Nodorum'
};

final Map<String, String> fieldLabelTranslations = {
  'severity': 'Tingkat Keparahan',
  'treatment': 'Pengobatan',
  'symptoms': 'Gejala',
  'description': 'Deskripsi',
  'spreading': 'Penyebaran',
  'prevention': 'Pencegahan',
  'chemical treatment': 'Pengobatan Kimia',
  'biological treatment': 'Pengobatan Biologis'
};

// Fungsi untuk mentranslasi respons API crop.health
Map<String, dynamic> translateCropHealthResponse(Map<String, dynamic> response, bool toIndonesian) {
  if (!toIndonesian) {
    // Jika tidak perlu diterjemahkan ke Bahasa Indonesia, kembalikan data asli
    return response;
  }
  
  // Deep copy response untuk menghindari perubahan pada data asli
  final translatedResponse = jsonDecode(jsonEncode(response));
  
  try {
    // BAGIAN PENTING: Translasi disease suggestions
    if (translatedResponse['result']?['disease']?['suggestions'] is List) {
      final suggestions = translatedResponse['result']['disease']['suggestions'] as List;
      
      for (int i = 0; i < suggestions.length; i++) {
        // Terjemahkan nama penyakit
        final diseaseName = suggestions[i]['name'];
        if (diseaseName != null && diseaseNameTranslations.containsKey(diseaseName)) {
          suggestions[i]['name'] = diseaseNameTranslations[diseaseName];
        }
        
        // Terjemahkan detail penyakit (bagian yang sering terlewat)
        if (suggestions[i]['details'] is Map<String, dynamic>) {
          final details = suggestions[i]['details'] as Map<String, dynamic>;
          
          // 1. Terjemahkan severity (bagian yang sering terlewat)
          if (details.containsKey('severity') && details['severity'] is String) {
            // Contoh terjemahan sederhana
            final severity = details['severity'] as String;
            details['severity'] = 'Tingkat Keparahan: ' + _getTranslatedText(severity);
          }
          
          // 2. Terjemahkan symptoms - perhatikan bahwa ini adalah Map<String, String>
          if (details.containsKey('symptoms') && details['symptoms'] is Map) {
            final symptoms = details['symptoms'] as Map;
            final translatedSymptoms = <String, String>{};
            
            symptoms.forEach((key, value) {
              // Terjemahkan key dan value dari symptoms
              final translatedKey = _getTranslatedText(key as String);
              final translatedValue = _getTranslatedText(value as String);
              translatedSymptoms[translatedKey] = translatedValue;
            });
            
            details['symptoms'] = translatedSymptoms;
          }
          
          // 3. Terjemahkan description
          if (details.containsKey('description') && details['description'] is String) {
            final description = details['description'] as String;
            details['description'] = _getTranslatedText(description);
          }
          
          // 4. Terjemahkan treatment - ini bisa berupa Map dengan arrays
          if (details.containsKey('treatment') && details['treatment'] is Map) {
            final treatment = details['treatment'] as Map;
            final translatedTreatment = <String, dynamic>{};
            
            treatment.forEach((key, value) {
              // Terjemahkan key dari treatment (prevention, chemical treatment, dll)
              final translatedKey = fieldLabelTranslations[key] ?? key;
              
              if (value is List) {
                // Terjemahkan setiap item dalam list
                final translatedList = (value as List).map((item) {
                  if (item is String) {
                    return _getTranslatedText(item);
                  }
                  return item;
                }).toList();
                
                translatedTreatment[translatedKey] = translatedList;
              } else {
                translatedTreatment[translatedKey] = value;
              }
            });
            
            details['treatment'] = translatedTreatment;
          }
          
          // 5. Terjemahkan spreading
          if (details.containsKey('spreading') && details['spreading'] is String) {
            final spreading = details['spreading'] as String;
            details['spreading'] = _getTranslatedText(spreading);
          }
          
          // 6. Update label untuk setiap field (penting untuk UI)
          // Tambahkan prefix pada setiap label field sehingga tampilan di UI akan terjemahkan
          final newDetails = <String, dynamic>{};
          details.forEach((key, value) {
            final translatedKey = fieldLabelTranslations[key] ?? key;
            newDetails[translatedKey] = value;
          });
          
          // Ganti details dengan versi yang sudah diterjemahkan
          suggestions[i]['details'] = newDetails;
        }
      }
    }
    
    // Translasi crop suggestions
    if (translatedResponse['result']?['crop']?['suggestions'] is List) {
      final suggestions = translatedResponse['result']['crop']['suggestions'] as List;
      
      for (int i = 0; i < suggestions.length; i++) {
        final cropName = suggestions[i]['name'];
        if (cropName != null && cropNameTranslations.containsKey(cropName)) {
          suggestions[i]['name'] = cropNameTranslations[cropName];
        }
      }
    }
    
    return translatedResponse;
  } catch (e) {
    print('Error dalam proses translasi: $e');
    // Jika terjadi error, kembalikan data asli
    return response;
  }
}

// Fungsi helper untuk simulasi translasi teks
// Dalam implementasi nyata, ini akan memanggil Google Gemini API atau layanan translasi lainnya
String _getTranslatedText(String originalText) {
  // Simulasi terjemahan sederhana untuk demonstrasi
  // Pada implementasi nyata, panggil API translasi di sini
  
  // Contoh terjemahan cepat untuk demonstrasi
  if (originalText.contains('severe')) {
    return originalText.replaceAll('severe', 'parah')
        .replaceAll('disease', 'penyakit')
        .replaceAll('crop', 'tanaman')
        .replaceAll('yield', 'hasil panen');
  }
  
  if (originalText.contains('symptoms')) {
    return originalText.replaceAll('symptoms', 'gejala')
        .replaceAll('leaves', 'daun')
        .replaceAll('disease', 'penyakit');
  }
  
  return 'Terjemahan untuk: ' + originalText.substring(0, min(50, originalText.length)) + '...';
}

// Helper function untuk string length min
int min(int a, int b) => a < b ? a : b;

void main() {
  // Parse respons API dari string JSON
  final originalResponse = jsonDecode(cropHealthResponse);
  
  // Panggil fungsi translasi
  final translatedResponse = translateCropHealthResponse(originalResponse, true);
  
  // Tampilkan hasil terjemahan
  print('\n=== STRUKTUR RESPONSE ASLI (ENGLISH) ===');
  final disease = originalResponse['result']['disease']['suggestions'][0];
  print('Disease name: ${disease['name']}');
  print('Severity: ${disease['details']['severity']}');
  print('Symptoms first key: ${(disease['details']['symptoms'] as Map).keys.first}');
  
  print('\n=== STRUKTUR RESPONSE YANG SUDAH DITERJEMAHKAN (INDONESIAN) ===');
  final translatedDisease = translatedResponse['result']['disease']['suggestions'][0];
  print('Nama penyakit: ${translatedDisease['name']}');
  
  // Perhatikan bahwa key 'severity' sudah berubah menjadi 'Tingkat Keparahan'
  final detailKeys = (translatedDisease['details'] as Map).keys.toList();
  print('Detail keys: $detailKeys');
  
  // Akses nilai severity setelah diterjemahkan (dengan key yang baru)
  final severityKey = detailKeys.firstWhere((key) => key.contains('Keparahan'), orElse: () => 'severity');
  print('$severityKey: ${translatedDisease['details'][severityKey]}');
  
  // Tampilkan symptoms setelah diterjemahkan
  final symptomsKey = detailKeys.firstWhere((key) => key.contains('Gejala'), orElse: () => 'symptoms');
  if (translatedDisease['details'][symptomsKey] is Map) {
    print('\nContoh gejala yang diterjemahkan:');
    final symptoms = translatedDisease['details'][symptomsKey] as Map;
    symptoms.forEach((key, value) {
      print('- $key: $value');
    });
  }
  
  // Tampilkan treatment setelah diterjemahkan
  final treatmentKey = detailKeys.firstWhere((key) => key.contains('Pengobatan'), orElse: () => 'treatment');
  if (translatedDisease['details'][treatmentKey] is Map) {
    print('\nContoh pengobatan yang diterjemahkan:');
    final treatment = translatedDisease['details'][treatmentKey] as Map;
    treatment.forEach((key, value) {
      print('$key:');
      if (value is List) {
        for (final item in value) {
          print('  - $item');
        }
      }
    });
  }
  
  print('\n=== POIN PENTING DALAM PENERJEMAHAN API CROP.HEALTH ===');
  print('1. Translasi harus menggunakan deep copy untuk menghindari mengubah data asli');
  print('2. Struktur respons API bersarang & kompleks, perlu translasi rekursif untuk setiap level');
  print('3. Beberapa field seperti symptoms berupa Map, bukan String sederhana');
  print('4. Treatment berisi nested lists yang juga perlu diterjemahkan');
  print('5. Untuk UI yang benar, kita perlu menerjemahkan baik key maupun value');
} 