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

import android.util.Log
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 {
    override suspend fun detectDisease(
        base64Image: String,
        prompt: String
    ): PlantDiseaseDetectionResponse {
        val request = GeminiRequest(
            contents = listOf(
                GeminiContent(
                    parts = listOf(
                        GeminiPart(text = prompt),
                        GeminiPart(inline_data = InlineData("image/jpeg", base64Image))
                    )
                )
            )
        )

        val response = api.detectDisease(
            apiKey = "AIzaSyDYZHlMfOdFAcTFptWHqhPwIO734VdNUWE", // Ideally use BuildConfig or secure storage
            request = request
        )
        Log.d("PlantDiagnosisRepository", "Response: $response")

        val rawJson = response.candidates.first().content.parts.first().text
        val cleanedJson = rawJson
            .replace("```json", "")
            .replace("```", "")
            .trim()
        return Json.decodeFromString(cleanedJson)
    }
}