package com.zhongqu.vrviewer.demojava;

import android.util.Log;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.WebView;
import com.zhongqu.vrviewer.x5host.TbsBootstrap;
import com.zhongqu.vrviewer.x5host.X5PublicDemoVerify;
import java.lang.ref.WeakReference;

/**
 * 内核验证与 {@code 3.0referenceDoc/publicDemo} 对齐：
 *
 * <ul>
 *   <li>MainActivity：{@code PreInitCallback.onViewInitFinished} → 日志「是否使用X5内核」由 {@link
 *       X5PublicDemoVerify#logPreInitViewFinished(boolean)} 在 {@link TbsBootstrap} 内打出
 *   <li>WebActivity：每次宿主 {@code loadUrl} 之后调用 {@link #onHostLoadUrlCompletedLikePublicDemo}，打
 *       {@code webactivity} 的 getTbsVersion 与 Toast 等价文案
 * </ul>
 */
public final class X5KernelVerification {

    private static final String TAG = "X5KernelVerify";
    private static final int POLL_INTERVAL_MS = 400;
    private static final int MAX_POLL_TICKS = 50;

    private static volatile Boolean sViewInitFinishedSuccess;
    private static volatile WeakReference<WebView> sHostWebView = new WeakReference<>(null);

    private X5KernelVerification() {}

    public static void markViewInitFinished(boolean success) {
        sViewInitFinishedSuccess = success;
    }

    @Nullable
    public static Boolean peekViewInitFinished() {
        return sViewInitFinishedSuccess;
    }

    public static void registerHostWebView(@Nullable WebView webView) {
        sHostWebView = new WeakReference<>(webView);
    }

    /**
     * 在宿主对带看页执行 {@code loadUrl} 之后调用（与 publicDemo WebActivity 在 loadUrl 后立刻验证一致）。
     */
    public static void onHostLoadUrlCompletedLikePublicDemo(
            @NonNull BaseViewerActivity activity, @NonNull WebView webView) {
        X5PublicDemoVerify.logAfterLoadUrlLikeWebActivity(activity, webView);
        activity.appendViewerDemoLog(
                "[X5验证/publicDemo-WebActivity] "
                        + X5PublicDemoVerify.describeRuntimeLikeWebActivityToast(activity, webView));
        appendSnapshotToDemo(activity, webView);
    }

    @NonNull
    public static String buildSnapshot(@NonNull android.content.Context context, @Nullable WebView webView) {
        Boolean preInit = sViewInitFinishedSuccess;
        String err = TbsBootstrap.getPipelineError();
        WebView wv = webView != null ? webView : sHostWebView.get();

        StringBuilder sb = new StringBuilder();
        sb.append(X5PublicDemoVerify.describePreInitViewFinished(preInit));
        if (err != null) {
            sb.append(" | 错误:").append(err);
        }
        sb.append(" | preInit核心就绪=").append(TbsBootstrap.isCoreReady());
        sb.append(" | canLoadX5=").append(QbSdk.canLoadX5(context));
        sb.append(" | tbsCoreVersion=").append(WebView.getTbsCoreVersion(context));

        if (wv == null) {
            sb.append(" | WebActivity验证:待进入带看并完成 loadUrl 后才有 getTbsVersion/getIsX5Core");
        } else {
            sb.append(" | ").append(X5PublicDemoVerify.describeRuntimeLikeWebActivityToast(context, wv));
            sb.append(" | getX5WebViewExtension=")
                    .append(wv.getX5WebViewExtension() != null ? "非空" : "null");
        }
        return sb.toString();
    }

    public static void appendSnapshotToDemo(
            @NonNull BaseViewerActivity activity, @Nullable WebView webView) {
        if (webView != null
                && TbsBootstrap.isCoreReady()
                && peekViewInitFinished() == null) {
            boolean inferred =
                    webView.getX5WebViewExtension() != null || webView.getIsX5Core();
            markViewInitFinished(inferred);
        }
        String body = buildSnapshot(activity, webView);
        Log.i(TAG, body);
        activity.appendViewerDemoLog("[X5验证] " + body);
    }

    public static void scheduleBannerRefresh(
            @NonNull BaseViewerActivity activity,
            @NonNull TextView kernelBanner,
            @NonNull String titleLine) {
        Runnable task =
                new Runnable() {
                    private int ticks;
                    private String lastBody = "";

                    @Override
                    public void run() {
                        if (activity.isFinishing()) {
                            return;
                        }
                        String body = buildSnapshot(activity, null);
                        kernelBanner.setText(titleLine + "\n" + body);
                        if (!body.equals(lastBody)) {
                            lastBody = body;
                            activity.appendViewerDemoLog("[X5验证] " + body);
                            Log.i(TAG, body);
                        }
                        ticks++;
                        if (ticks < MAX_POLL_TICKS) {
                            kernelBanner.postDelayed(this, POLL_INTERVAL_MS);
                        }
                    }
                };
        kernelBanner.post(task);
    }
}
