package com.tencent.qian.webview;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.tencent.qian.webview.internal.IntentBridge;
import com.tencent.qian.webview.model.SignCallback;
import com.tencent.qian.webview.model.TencentQianWebViewConfig;

/**
 * <b>容器模式</b>：SDK 全包接管，客户 1 行调用即可。
 *
 * <p>典型用法：
 * <pre>{@code
 * TencentQianWebView.open(activity, signUrl,
 *     TencentQianWebViewConfig.builder().topBarTitle("电子签署").build(),
 *     new SignCallback() {
 *         public void onSignResult(SignResult result) { ... }
 *     });
 * }</pre>
 */
public final class TencentQianWebView {

    private TencentQianWebView() {}

    /**
     * 启动签署容器（完整参数）。
     */
    public static void open(
            @NonNull Activity activity,
            @NonNull String url,
            @NonNull TencentQianWebViewConfig config,
            @Nullable SignCallback callback
    ) {
        // 预热环境错配检测（best-effort，仅告警，不阻断）
        TencentQianWebViewPrewarmer.warnIfEnvironmentMismatch(url);
        IntentBridge.put(callback, config);
        Intent intent = new Intent(activity, TencentQianWebViewActivity.class);
        intent.putExtra(TencentQianWebViewActivity.EXTRA_URL, url);
        activity.startActivity(intent);
    }

    /**
     * 启动签署容器（默认配置，无回调）。
     */
    public static void open(@NonNull Activity activity, @NonNull String url) {
        open(activity, url, TencentQianWebViewConfig.DEFAULT, null);
    }

    /**
     * 启动签署容器（带回调，默认配置）。
     */
    public static void open(@NonNull Activity activity, @NonNull String url, @Nullable SignCallback callback) {
        open(activity, url, TencentQianWebViewConfig.DEFAULT, callback);
    }

    /**
     * 启动「自检页」容器。
     */
    public static void openCompatibilityTest(
            @NonNull Activity activity,
            @Nullable String customUrl,
            @NonNull TencentQianWebViewConfig config,
            @Nullable SignCallback callback
    ) {
        String finalUrl = customUrl;
        if (finalUrl == null || finalUrl.isEmpty()) {
            finalUrl = config.getCompatibilityTestUrl();
        }
        if (finalUrl == null || finalUrl.isEmpty()) {
            finalUrl = TencentQianWebViewConfig.DEFAULT_COMPATIBILITY_TEST_URL;
        }
        TencentQianWebViewConfig testConfig = TencentQianWebViewConfig.builder()
                .showTopBar(config.isShowTopBar())
                .topBarTitle(activity.getString(R.string.qian_compatibility_test_title))
                .topBarBackgroundColor(config.getTopBarBackgroundColor())
                .topBarTextColor(config.getTopBarTextColor())
                .showCloseButton(config.isShowCloseButton())
                .statusBarStyle(config.getStatusBarStyle())
                .injectUserAgent(config.isInjectUserAgent())
                .userAgentExtra(config.getUserAgentExtra())
                .allowMixedContent(config.getAllowMixedContent())
                .confirmBeforeClose(config.isConfirmBeforeClose())
                .confirmCloseTitle(config.getConfirmCloseTitle())
                .confirmCloseMessage(config.getConfirmCloseMessage())
                .externalSchemes(config.getExternalSchemes())
                .compatibilityTestUrl(config.getCompatibilityTestUrl())
                .jsDialogStyle(config.getJsDialogStyle())
                .downloadWithCookies(config.isDownloadWithCookies())
                .legacyFaceCaptureMimeTypes(config.getLegacyFaceCaptureMimeTypes())
                .cameraCaptureBehavior(config.getCameraCaptureBehavior())
                .build();
        open(activity, finalUrl, testConfig, callback);
    }

    /**
     * 启动「自检页」容器（简化参数）。
     */
    public static void openCompatibilityTest(@NonNull Activity activity, @Nullable String customUrl, @Nullable SignCallback callback) {
        openCompatibilityTest(activity, customUrl, TencentQianWebViewConfig.DEFAULT, callback);
    }

    /**
     * 查询 SDK 版本号。
     */
    @NonNull
    public static String sdkVersion() {
        return "1.2.0";
    }

    /**
     * 判断 URI 是否由 SDK 处理。
     */
    public static boolean canHandle(@Nullable Uri uri) {
        if (uri == null) return false;
        String s = uri.getScheme();
        if (s == null) return false;
        return "qianapp".equalsIgnoreCase(s);
    }
}
