// 连接状态调试工具
// 用于诊断连接后一直显示 connecting 的问题

import 'package:get/get.dart';
import 'package:kaer_with_panels/app/services/singbox_imp/kr_sing_box_imp.dart';
import 'package:kaer_with_panels/app/modules/kr_home/controllers/kr_home_controller.dart';
import 'package:kaer_with_panels/app/localization/app_translations.dart';

class ConnectionStatusDebugger {
  static void debugConnectionStatus() {
    print('🔍 === 连接状态调试信息 ===');
    
    // 1. 检查 SingBox 状态
    final singboxStatus = KRSingBoxImp.instance.kr_status.value;
    print('📊 SingBox 状态: $singboxStatus');
    print('📊 SingBox 状态类型: ${singboxStatus.runtimeType}');
    
    // 2. 检查首页控制器状态
    try {
      final homeController = Get.find<KRHomeController>();
      print('🏠 首页控制器连接文本: ${homeController.kr_connectText.value}');
      print('🏠 首页控制器是否连接: ${homeController.kr_isConnected.value}');
      print('🏠 首页控制器当前速度: ${homeController.kr_currentSpeed.value}');
      print('🏠 首页控制器节点延迟: ${homeController.kr_currentNodeLatency.value}');
    } catch (e) {
      print('❌ 无法获取首页控制器: $e');
    }
    
    // 3. 检查活动组
    final activeGroups = KRSingBoxImp.instance.kr_activeGroups;
    print('📋 活动组数量: ${activeGroups.length}');
    for (int i = 0; i < activeGroups.length; i++) {
      final group = activeGroups[i];
      print('  └─ 组[$i]: tag=${group.tag}, type=${group.type}, selected=${group.selected}');
    }
    
    // 4. 检查状态监听器
    print('🔄 状态监听器状态:');
    KRSingBoxImp.instance.kr_status.listen((status) {
      print('  └─ 状态变化: $status (${status.runtimeType})');
    });
    
    print('🔍 === 调试信息结束 ===');
  }
  
  static void forceStatusSync() {
    print('🔄 强制同步连接状态...');
    try {
      final homeController = Get.find<KRHomeController>();
      homeController.kr_forceSyncConnectionStatus();
      print('✅ 状态同步完成');
    } catch (e) {
      print('❌ 状态同步失败: $e');
    }
  }
  
  static void testConnectionFlow() {
    print('🧪 测试连接流程...');
    
    // 模拟连接流程
    print('1. 开始连接...');
    KRSingBoxImp.instance.kr_start().then((_) {
      print('2. 连接启动完成');
      
      // 等待状态更新
      Future.delayed(const Duration(seconds: 3), () {
        print('3. 检查连接状态...');
        debugConnectionStatus();
      });
    }).catchError((e) {
      print('❌ 连接失败: $e');
    });
  }
}
