package com.tencent.qian.webview.prewarm

import org.json.JSONObject

/**
 * `warmup-manifest.json` 数据模型（三端结构一致）。由前端构建产出，SDK 只读消费。
 */
internal data class WarmupBizType(
    val warmupUrl: String,
    val assets: List<String>
)

/** manifest 顶层结构。 */
internal data class WarmupManifest(
    val version: String,
    val hosts: List<String>,
    val bizTypes: Map<String, WarmupBizType>,
    val menuBizTypes: List<String>?
) {
    internal companion object {

        /** 从 JSON 文本解析；解析失败返回 `null`（best-effort）。 */
        fun parse(json: String): WarmupManifest? {
            return try {
                val root = JSONObject(json)
                val version = root.optString("version", "")
                val hostsArr = root.optJSONArray("hosts") ?: return null
                val hosts = ArrayList<String>(hostsArr.length())
                for (i in 0 until hostsArr.length()) {
                    hosts.add(hostsArr.optString(i))
                }
                val bizTypes = HashMap<String, WarmupBizType>()
                val bizObj = root.optJSONObject("bizTypes")
                if (bizObj != null) {
                    val keys = bizObj.keys()
                    while (keys.hasNext()) {
                        val key = keys.next()
                        val biz = bizObj.optJSONObject(key) ?: continue
                        val warmupUrl = biz.optString("warmupUrl", "")
                        val assetsArr = biz.optJSONArray("assets")
                        val assets = ArrayList<String>(assetsArr?.length() ?: 0)
                        if (assetsArr != null) {
                            for (i in 0 until assetsArr.length()) {
                                assets.add(assetsArr.optString(i))
                            }
                        }
                        bizTypes[key] = WarmupBizType(warmupUrl, assets)
                    }
                }
                val menuBizTypes: List<String>? = root.optJSONArray("menuBizTypes")?.let { arr ->
                    (0 until arr.length()).map { arr.optString(it) }
                }
                WarmupManifest(version, hosts, bizTypes, menuBizTypes)
            } catch (_: Throwable) {
                null
            }
        }
    }
}
