import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/foundation.dart';
import 'telemetry_event.dart';
import '../presence/presence_config.dart';

/// 遥测配置
/// 支持远程配置和本地缓存
class TelemetryConfig {
  // 全局开关
  bool globalEnabled = true;

  // 分类型开关
  bool errorReportEnabled = true; // 错误上报
  bool performanceEnabled = true; // 性能监控
  bool userActionEnabled = true; // 用户行为
  bool pageViewEnabled = true; // 页面访问
  bool sessionEnabled = true; // 会话事件（DAU相关）

  // 采样配置
  double samplingRate = 0.1; // 10% 采样率

  // 事件黑名单
  List<String> disabledEvents = [];

  // 配置版本
  String configVersion = '1.0.0';

  // 用户是否同意（可选，用于隐私合规）
  bool userOptIn = true;

  // 心跳/在线状态配置
  PresenceConfig? presenceConfig;

  static final TelemetryConfig _instance = TelemetryConfig._();
  TelemetryConfig._();
  factory TelemetryConfig() => _instance;

  /// 从后端同步配置
  Future<void> syncFromRemote(String apiBaseUrl) async {
    try {
      final dio = Dio(BaseOptions(
        connectTimeout: const Duration(seconds: 5),
        receiveTimeout: const Duration(seconds: 5),
      ));
      // apiBaseUrl 已经包含 /api/v1，所以这里只需要添加相对路径
      final response = await dio.get('$apiBaseUrl/telemetry/config');
      final data = response.data;

      globalEnabled = data['global_enabled'] ?? true;
      errorReportEnabled = data['error_report_enabled'] ?? true;
      performanceEnabled = data['performance_enabled'] ?? true;
      userActionEnabled = data['user_action_enabled'] ?? true;
      pageViewEnabled = data['page_view_enabled'] ?? true;
      sessionEnabled = data['session_enabled'] ?? true;
      samplingRate = (data['sampling_rate'] ?? 0.1).toDouble();
      disabledEvents = List<String>.from(data['disabled_events'] ?? []);
      configVersion = data['version'] ?? '1.0.0';

      // 解析心跳配置
      if (data['presence_config'] != null) {
        presenceConfig = PresenceConfig.fromJson(data['presence_config']);
      }

      // 缓存到本地
      await _saveToLocal();

      debugPrint('📊 Telemetry config synced (v$configVersion)');
      debugPrint(
          '   Global: $globalEnabled, Sampling: ${(samplingRate * 100).toInt()}%');
      debugPrint('   Presence: ${presenceConfig?.enabled ?? true}');
    } catch (e) {
      debugPrint('⚠️ Failed to sync telemetry config: $e');
      // 失败时加载本地缓存
      await _loadFromLocal();
    }
  }

  /// 保存到本地
  Future<void> _saveToLocal() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('telemetry_global_enabled', globalEnabled);
    await prefs.setBool('telemetry_error_enabled', errorReportEnabled);
    await prefs.setBool('telemetry_performance_enabled', performanceEnabled);
    await prefs.setBool('telemetry_user_action_enabled', userActionEnabled);
    await prefs.setBool('telemetry_page_view_enabled', pageViewEnabled);
    await prefs.setBool('telemetry_session_enabled', sessionEnabled);
    await prefs.setDouble('telemetry_sampling_rate', samplingRate);
    await prefs.setStringList('telemetry_disabled_events', disabledEvents);
    await prefs.setString('telemetry_config_version', configVersion);
  }

  /// 从本地加载
  Future<void> _loadFromLocal() async {
    final prefs = await SharedPreferences.getInstance();
    globalEnabled = prefs.getBool('telemetry_global_enabled') ?? true;
    errorReportEnabled = prefs.getBool('telemetry_error_enabled') ?? true;
    performanceEnabled =
        prefs.getBool('telemetry_performance_enabled') ?? true;
    userActionEnabled = prefs.getBool('telemetry_user_action_enabled') ?? true;
    pageViewEnabled = prefs.getBool('telemetry_page_view_enabled') ?? true;
    sessionEnabled = prefs.getBool('telemetry_session_enabled') ?? true;
    samplingRate = prefs.getDouble('telemetry_sampling_rate') ?? 0.1;
    disabledEvents = prefs.getStringList('telemetry_disabled_events') ?? [];
    configVersion = prefs.getString('telemetry_config_version') ?? '1.0.0';
  }

  /// 判断是否应该记录该事件
  bool shouldLog(EventType type, String eventName) {
    // 1. 全局开关
    if (!globalEnabled) return false;

    // 2. 用户未同意
    if (!userOptIn) return false;

    // 3. 事件黑名单
    if (disabledEvents.contains(eventName)) return false;

    // 4. 分类型判断
    switch (type) {
      case EventType.error:
      case EventType.crash:
        return errorReportEnabled;
      case EventType.performance:
        return performanceEnabled;
      case EventType.userAction:
        return userActionEnabled;
      case EventType.pageView:
        return pageViewEnabled;
      case EventType.apiCall:
        return performanceEnabled; // API调用归入性能监控
      case EventType.session:
        return sessionEnabled; // 会话事件
      case EventType.presence:
        return presenceConfig?.enabled ?? true; // 在线状态
    }
  }

  /// 设置用户是否同意
  Future<void> setUserOptIn(bool optIn) async {
    userOptIn = optIn;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('telemetry_user_opt_in', optIn);
    debugPrint('📊 User opt-in: $optIn');
  }

  /// 加载用户选择
  Future<void> loadUserOptIn() async {
    final prefs = await SharedPreferences.getInstance();
    userOptIn = prefs.getBool('telemetry_user_opt_in') ?? true;
  }
}
