package com.narutohuo.xindazhou.core.network.converter

import com.alibaba.fastjson2.JSON
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 * FastJson Converter Factory（工厂模式）
 * 
 * 用于 Retrofit 的 JSON 转换，替代 Gson
 * 
 * 使用方式：
 * ```kotlin
 * Retrofit.Builder()
 *     .addConverterFactory(FastJsonConverterFactory.create())
 *     .build()
 * ```
 */
class FastJsonConverterFactory private constructor() : Converter.Factory() {
    
    companion object {
        private val MEDIA_TYPE: MediaType = "application/json; charset=UTF-8".toMediaType()
        
        /**
         * 创建 FastJson Converter Factory 实例（工厂方法）
         */
        @JvmStatic
        fun create(): FastJsonConverterFactory {
            return FastJsonConverterFactory()
        }
    }
    
    override fun requestBodyConverter(
        type: Type,
        parameterAnnotations: Array<Annotation>,
        methodAnnotations: Array<Annotation>,
        retrofit: Retrofit
    ): Converter<*, RequestBody>? {
        return RequestBodyConverter<Any>()
    }
    
    override fun responseBodyConverter(
        type: Type,
        annotations: Array<Annotation>,
        retrofit: Retrofit
    ): Converter<ResponseBody, *>? {
        return ResponseBodyConverter<Any>(type)
    }
    
    /**
     * 请求体转换器（将对象转换为 JSON RequestBody）
     */
    private class RequestBodyConverter<T> : Converter<T, RequestBody> {
        @Suppress("UNCHECKED_CAST")
        override fun convert(value: T): RequestBody? {
            val json = JSON.toJSONString(value)
            return json.toRequestBody(MEDIA_TYPE)
        }
    }
    
    /**
     * 响应体转换器（将 JSON ResponseBody 转换为对象）
     * 
     * 对于 CommonResult<T> 类型，解析为 CommonResult<Map>，然后在 ApiResponseParser 中统一处理类型转换
     * 这样可以避免 Fastjson2 在解析嵌套泛型时的类型擦除问题
     */
    private class ResponseBodyConverter<T>(
        private val type: Type
    ) : Converter<ResponseBody, T> {
        @Suppress("UNCHECKED_CAST")
        override fun convert(value: ResponseBody): T {
            val json = value.string()
            try {
                com.narutohuo.xindazhou.core.log.ILog.d("FastJsonConverter", "解析JSON: type=${type}, json=${json.take(200)}...")
                
                // Fastjson2 支持嵌套泛型，直接使用 parseObject 即可
                // 对于 ParameterizedType（如 CommonResult<LoginResponse>），Fastjson2 会自动处理
                val result = JSON.parseObject(json, type) as T
                
                // 检查解析结果
                if (result != null && type is ParameterizedType) {
                    val rawType = type.rawType
                    val rawTypeName = (rawType as? Class<*>)?.name ?: ""
                    if (rawTypeName.contains("CommonResult")) {
                        try {
                            val dataField = result.javaClass.getDeclaredField("data")
                            dataField.isAccessible = true
                            val dataValue = dataField.get(result)
                            com.narutohuo.xindazhou.core.log.ILog.d("FastJsonConverter", "解析成功: ${result.javaClass.simpleName}, data类型=${dataValue?.javaClass?.simpleName ?: "null"}")
                        } catch (e: Exception) {
                            com.narutohuo.xindazhou.core.log.ILog.e("FastJsonConverter", "检查 data 字段失败: ${e.message}", e)
                        }
                    }
                } else {
                    com.narutohuo.xindazhou.core.log.ILog.d("FastJsonConverter", "解析成功: ${result?.let { it::class.java.simpleName } ?: "null"}")
                }
                
                return result
                
            } catch (e: Exception) {
                com.narutohuo.xindazhou.core.log.ILog.e("FastJsonConverter", "JSON解析失败: type=${type}, json=${json.take(500)}", e)
                throw e
            }
        }
    }
}

