package com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.repository

import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.core.extention.DiagnosisResult
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.model.ErrorResponse
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.model.GeminiContent
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.model.GeminiPart
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.model.GeminiRequest
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.model.InlineData
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.model.PlantDiseaseDetectionResponse
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.network.GeminiApiService
import kotlinx.serialization.json.Json

class PlantDiagnosisRepositoryImpl(private val api: GeminiApiService) : PlantDiagnosisRepository {
    private val json = Json { ignoreUnknownKeys = true }
    override suspend fun detectDisease(
        base64Image: String,
        prompt: String
    ): DiagnosisResult {
        return try {
            val request = GeminiRequest(
                contents = listOf(
                    GeminiContent(
                        parts = listOf(
                            GeminiPart(text = prompt),
                            GeminiPart(inline_data = InlineData("image/jpeg", base64Image))
                        )
                    )
                )
            )
            val response = api.detectDisease(
                apiKey = "AIzaSyDYZHlMfOdFAcTFptWHqhPwIO734VdNUWE",
                request = request
            )

            val rawJson = response.candidates.first().content.parts.first().text
            val cleanedJson = rawJson
                .replace("```json", "")
                .replace("```", "")
                .trim()
            try {
                val parsedSuccess =
                    json.decodeFromString<PlantDiseaseDetectionResponse>(cleanedJson)
                DiagnosisResult.Success(parsedSuccess)
            } catch (e: Exception) {
                val parsedError = json.decodeFromString<ErrorResponse>(cleanedJson)
                DiagnosisResult.Error(parsedError.error.toString())
            }
        } catch (e: Exception) {
            DiagnosisResult.Error("Terjadi kesalahan: ${e.localizedMessage ?: "tidak diketahui"}")
        }
    }
}


