code

// ============================================
// 1. 核心接口定义
// ============================================

/**
 * JSON 序列化/反序列化异常
 */
class JsonException(message: String, cause: Throwable? = null) : Exception(message, cause)

/**
 * 类型引用,用于处理泛型类型
 */
abstract class TypeRef<T> {
    val type: java.lang.reflect.Type = 
        (javaClass.genericSuperclass as java.lang.reflect.ParameterizedType)
            .actualTypeArguments[0]
}

/**
 * JSON 编解码器接口
 */
interface JsonCodec {
    /**
     * 将对象序列化为 JSON 字符串
     */
    fun <T> toJson(value: T): String
    
    /**
     * 将对象序列化到输出流
     */
    fun <T> toJson(value: T, output: java.io.OutputStream)
    
    /**
     * 从 JSON 字符串反序列化
     */
    fun <T> fromJson(json: String, type: java.lang.reflect.Type): T?
    
    /**
     * 从输入流反序列化
     */
    fun <T> fromJson(input: java.io.InputStream, type: java.lang.reflect.Type): T?
}

// ============================================
// 2. Moshi 实现
// ============================================

import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okio.buffer
import okio.sink
import okio.source

class MoshiCodec(
    private val moshi: Moshi = Moshi.Builder()
        .add(KotlinJsonAdapterFactory())
        .build()
) : JsonCodec {
    
    override fun <T> toJson(value: T): String {
        return try {
            @Suppress("UNCHECKED_CAST")
            val adapter = moshi.adapter<T>(value!!::class.java as Class<T>)
            adapter.toJson(value)
        } catch (e: Exception) {
            throw JsonException("Failed to serialize to JSON", e)
        }
    }
    
    override fun <T> toJson(value: T, output: java.io.OutputStream) {
        try {
            @Suppress("UNCHECKED_CAST")
            val adapter = moshi.adapter<T>(value!!::class.java as Class<T>)
            val sink = output.sink().buffer()
            adapter.toJson(sink, value)
            sink.flush()
        } catch (e: Exception) {
            throw JsonException("Failed to serialize to JSON stream", e)
        }
    }
    
    override fun <T> fromJson(json: String, type: java.lang.reflect.Type): T? {
        return try {
            val adapter = moshi.adapter<T>(type)
            adapter.fromJson(json)
        } catch (e: Exception) {
            throw JsonException("Failed to deserialize from JSON", e)
        }
    }
    
    override fun <T> fromJson(input: java.io.InputStream, type: java.lang.reflect.Type): T? {
        return try {
            val adapter = moshi.adapter<T>(type)
            val source = input.source().buffer()
            adapter.fromJson(source)
        } catch (e: Exception) {
            throw JsonException("Failed to deserialize from JSON stream", e)
        }
    }
}

// ============================================
// 3. Jackson 实现(可选)
// ============================================

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule

class JacksonCodec(
    private val mapper: ObjectMapper = ObjectMapper().registerKotlinModule()
) : JsonCodec {
    
    override fun <T> toJson(value: T): String {
        return try {
            mapper.writeValueAsString(value)
        } catch (e: Exception) {
            throw JsonException("Failed to serialize to JSON", e)
        }
    }
    
    override fun <T> toJson(value: T, output: java.io.OutputStream) {
        try {
            mapper.writeValue(output, value)
        } catch (e: Exception) {
            throw JsonException("Failed to serialize to JSON stream", e)
        }
    }
    
    override fun <T> fromJson(json: String, type: java.lang.reflect.Type): T? {
        return try {
            mapper.readValue(json, mapper.constructType(type))
        } catch (e: Exception) {
            throw JsonException("Failed to deserialize from JSON", e)
        }
    }
    
    override fun <T> fromJson(input: java.io.InputStream, type: java.lang.reflect.Type): T? {
        return try {
            mapper.readValue(input, mapper.constructType(type))
        } catch (e: Exception) {
            throw JsonException("Failed to deserialize from JSON stream", e)
        }
    }
}

// ============================================
// 4. Request 类集成
// ============================================

class Request(
    val body: java.io.InputStream,
    private val codec: JsonCodec = MoshiCodec()
) {
    
    private var cachedBody: String? = null
    
    /**
     * Kotlin 用户:使用 reified 泛型
     */
    inline fun <reified T> json(): T? {
        return json(object : TypeRef<T>() {}.type)
    }
    
    /**
     * Java 用户:使用 Class
     */
    fun <T> json(clazz: Class<T>): T? {
        return json(clazz as java.lang.reflect.Type)
    }
    
    /**
     * Java 用户:使用 TypeRef 处理复杂类型
     * 
     * 用法示例:
     * - List<User>: request.json(new TypeRef<List<User>>() {})
     * - Map<String, User>: request.json(new TypeRef<Map<String, User>>() {})
     */
    fun <T> json(typeRef: TypeRef<T>): T? {
        return json(typeRef.type)
    }
    
    /**
     * 内部实现:根据 Type 反序列化
     */
    private fun <T> json(type: java.lang.reflect.Type): T? {
        // 优先使用流式反序列化(性能更好)
        return try {
            if (body.markSupported()) {
                body.mark(Int.MAX_VALUE)
                try {
                    codec.fromJson<T>(body, type)
                } catch (e: Exception) {
                    // 如果流式失败,回退到字符串方式
                    body.reset()
                    val bodyStr = getBodyAsString()
                    codec.fromJson(bodyStr, type)
                }
            } else {
                // 流不支持 mark,使用字符串方式
                val bodyStr = getBodyAsString()
                codec.fromJson(bodyStr, type)
            }
        } catch (e: JsonException) {
            throw e
        } catch (e: Exception) {
            throw JsonException("Failed to parse JSON from request body", e)
        }
    }
    
    private fun getBodyAsString(): String {
        if (cachedBody == null) {
            cachedBody = body.bufferedReader().use { it.readText() }
        }
        return cachedBody!!
    }
}

// ============================================
// 5. Response 类集成(额外提供)
// ============================================

class Response(
    private val outputStream: java.io.OutputStream,
    private val codec: JsonCodec = MoshiCodec()
) {
    
    /**
     * 将对象序列化为 JSON 并写入响应
     */
    fun <T> json(value: T): Response {
        try {
            setHeader("Content-Type", "application/json; charset=utf-8")
            codec.toJson(value, outputStream)
            return this
        } catch (e: JsonException) {
            throw e
        } catch (e: Exception) {
            throw JsonException("Failed to write JSON response", e)
        }
    }
    
    private fun setHeader(name: String, value: String) {
        // 设置响应头的实现
    }
}

// ============================================
// 6. 使用示例
// ============================================

data class User(val id: Int, val name: String, val email: String)

fun examples() {
    val request = Request(System.`in`)
    
    // Kotlin 用户 - 简单类型
    val user: User? = request.json<User>()
    
    // Kotlin 用户 - 复杂类型
    val users: List<User>? = request.json<List<User>>()
    val userMap: Map<String, User>? = request.json<Map<String, User>>()
    
    // Java 用户 - 简单类型
    val user2: User? = request.json(User::class.java)
    
    // Java 用户 - 复杂类型
    val users2: List<User>? = request.json(object : TypeRef<List<User>>() {})
    val userMap2: Map<String, User>? = request.json(object : TypeRef<Map<String, User>>() {})
}

// ============================================
// 7. 配置和扩展
// ============================================

/**
 * JSON 配置构建器
 */
class JsonConfig {
    var codec: JsonCodec = MoshiCodec()
    
    fun useMoshi(configure: (Moshi.Builder) -> Unit = {}) {
        val builder = Moshi.Builder()
        configure(builder)
        builder.add(KotlinJsonAdapterFactory())
        codec = MoshiCodec(builder.build())
    }
    
    fun useJackson(configure: (ObjectMapper) -> Unit = {}) {
        val mapper = ObjectMapper().registerKotlinModule()
        configure(mapper)
        codec = JacksonCodec(mapper)
    }
    
    fun useCustom(codec: JsonCodec) {
        this.codec = codec
    }
}

/**
 * 应用级别配置示例
 */
object JsonConfigHolder {
    var defaultCodec: JsonCodec = MoshiCodec()
    
    fun configure(block: JsonConfig.() -> Unit) {
        val config = JsonConfig()
        config.block()
        defaultCodec = config.codec
    }
}

// 配置示例
fun configureJson() {
    JsonConfigHolder.configure {
        useMoshi { builder ->
            // 添加自定义适配器
            // builder.add(CustomAdapter())
        }
    }
}