package com.tencent.qian.webview.scheme

import android.os.Handler
import android.os.Looper
import com.tencent.qian.webview.model.SdkEvent
import com.tencent.qian.webview.model.SignCallback
import com.tencent.qian.webview.model.SignResult

/**
 * `qianapp://` scheme 拦截器(纯逻辑层,不依赖 Android Context)。
 *
 * **职责**:
 * - 判断 URL 是否为 `qianapp://` scheme
 * - 解析后通过 [callbackProvider] 拿到当前 [SignCallback] 派发结果
 * - 派发严格在主线程
 *
 * 与 iOS `SchemeInterceptor.swift` 1:1 对齐。
 */
internal class SchemeInterceptor(
    private val callbackProvider: () -> SignCallback?
) {

    private val mainHandler = Handler(Looper.getMainLooper())

    /**
     * 尝试拦截 URL。
     *
     * @return `true` 已识别并处理(WebView 应 cancel 加载),`false` 未识别(WebView 继续默认处理)
     */
    fun handle(url: String?): Boolean {
        if (!SignResultParser.isQianAppScheme(url)) return false

        val result: SignResult = SignResultParser.parse(url)
        val cb = callbackProvider()

        dispatchOnMain {
            cb?.onSignResult(result)
            cb?.onEvent(SdkEvent.SchemeIntercepted(scheme = "qianapp", url = url ?: ""))
        }
        return true
    }

    private fun dispatchOnMain(block: () -> Unit) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            block()
        } else {
            mainHandler.post(block)
        }
    }
}
