package eu.gaudian.translator.model.communication

import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import java.lang.reflect.Type

/**
 * Robust models for Wiktionary parse API that accept either an object {"*": "<html>"}
 * or a raw string for the `text` field.
 */
 data class WiktionaryResponse(
     val parse: ParseData?
 )

 data class ParseData(
     val title: String?,
     val text: TextField?
 )

 /** Wrapper for the flexible `text` payload. */
 data class TextField(
     val html: String?
 )

 /** Gson deserializer that accepts either object-with-star or raw string. */
 class TextFieldDeserializer : JsonDeserializer<TextField> {
     override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): TextField {
         if (json == null || json.isJsonNull) return TextField(null)
         return try {
             when {
                 json.isJsonPrimitive && json.asJsonPrimitive.isString -> TextField(json.asString)
                 json.isJsonObject -> {
                     val obj = json.asJsonObject
                     val star = obj.get("*")
                     val html = if (star != null && !star.isJsonNull) star.asString else null
                     TextField(html)
                 }
                 else -> TextField(null)
             }
         } catch (_: Exception) {
             TextField(null)
         }
     }
 }