import 'dart:io';
import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:kaer_with_panels/app/services/singbox_imp/kr_sing_box_imp.dart';
import 'package:kaer_with_panels/app/utils/kr_log_util.dart';

class KRHttpAdapterUtil {
  /// 创建标准配置的 HttpClientAdapter
  /// 
  /// [useSingBoxProxy] 是否集成 sing-box 代理规则，默认 true
  /// [forceDirect] 是否强制直连（不使用任何代理），默认 false
  static HttpClientAdapter createAdapter({
    bool useSingBoxProxy = true,
    bool forceDirect = false,
    Duration timeout = const Duration(seconds: 10),
  }) {
    return IOHttpClientAdapter(
      createHttpClient: () {
        final client = HttpClient();
        client.connectionTimeout = timeout;
        
        // ✅ 统一修复：允许所有 SSL 证书
        client.badCertificateCallback = (cert, host, port) => true;

        if (forceDirect) {
          client.findProxy = (url) {
            KRLogUtil.kr_i('🔍 请求使用直连: $url', tag: 'KRHttpAdapterUtil');
            return 'DIRECT';
          };
        } else if (useSingBoxProxy) {
          client.findProxy = (url) {
            try {
              final proxyConfig = KRSingBoxImp.instance.kr_buildProxyRule();
              // KRLogUtil.kr_i('🔍 请求使用代理: $proxyConfig, url: $url', tag: 'KRHttpAdapterUtil');
              return proxyConfig;
            } catch (e) {
              KRLogUtil.kr_w('⚠️ 获取代理配置异常，回退到 DIRECT: $e', tag: 'KRHttpAdapterUtil');
              return 'DIRECT';
            }
          };
        }
        
        return client;
      },
    );
  }
}
