import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/foundation.dart';
import '../models/telemetry_event.dart';

/// 遥测本地存储
/// 负责缓存事件队列和设备上下文
class TelemetryStorage {
  static const String _keyEventQueue = 'telemetry_event_queue';
  static const String _keyDeviceContext = 'telemetry_device_context';
  static const String _keyInstallId = 'telemetry_install_id';
  static const int _maxQueueSize = 500; // 最多缓存500条

  late SharedPreferences _prefs;
  bool _isInitialized = false;

  /// 初始化
  Future<void> init() async {
    if (_isInitialized) return;
    _prefs = await SharedPreferences.getInstance();
    _isInitialized = true;
  }

  /// 保存设备上下文
  Future<void> saveDeviceContext(Map<String, dynamic> context) async {
    await _prefs.setString(_keyDeviceContext, jsonEncode(context));
  }

  /// 读取设备上下文
  Map<String, dynamic>? getDeviceContext() {
    final str = _prefs.getString(_keyDeviceContext);
    if (str == null) return null;
    return jsonDecode(str) as Map<String, dynamic>;
  }

  /// 保存 InstallId
  Future<void> saveInstallId(String installId) async {
    await _prefs.setString(_keyInstallId, installId);
  }

  /// 读取 InstallId
  String? getInstallId() {
    return _prefs.getString(_keyInstallId);
  }

  /// 添加事件到队列
  Future<void> enqueueEvent(TelemetryEvent event) async {
    final queue = _getEventQueue();

    // 防止队列过大
    if (queue.length >= _maxQueueSize) {
      queue.removeAt(0); // 移除最旧的
      debugPrint('⚠️ Telemetry queue full, removed oldest event');
    }

    queue.add(event.toJson());
    await _saveEventQueue(queue);
  }

  /// 批量添加事件
  Future<void> enqueueEvents(List<TelemetryEvent> events) async {
    final queue = _getEventQueue();

    for (var event in events) {
      if (queue.length >= _maxQueueSize) break;
      queue.add(event.toJson());
    }

    await _saveEventQueue(queue);
  }

  /// 获取待上传的事件(最多N条)
  List<TelemetryEvent> dequeueEvents(int limit) {
    final queue = _getEventQueue();
    final count = queue.length > limit ? limit : queue.length;

    final events = queue
        .take(count)
        .map((json) => TelemetryEvent.fromJson(json))
        .toList();

    return events;
  }

  /// 删除已上传的事件
  Future<void> removeEvents(int count) async {
    final queue = _getEventQueue();
    if (count >= queue.length) {
      await clearEventQueue();
    } else {
      queue.removeRange(0, count);
      await _saveEventQueue(queue);
    }
  }

  /// 获取队列长度
  int getQueueSize() {
    return _getEventQueue().length;
  }

  /// 清空事件队列
  Future<void> clearEventQueue() async {
    await _prefs.remove(_keyEventQueue);
  }

  /// 清空所有遥测数据（退出登录时调用）
  /// 保留 installId 和 deviceContext（设备级别数据）
  Future<void> clearUserData() async {
    if (!_isInitialized) {
      await init();
    }
    await _prefs.remove(_keyEventQueue);
    debugPrint('📊 TelemetryStorage: 已清除用户相关遥测数据');
  }

  // 私有方法
  List<Map<String, dynamic>> _getEventQueue() {
    final str = _prefs.getString(_keyEventQueue);
    if (str == null) return [];

    try {
      final List<dynamic> list = jsonDecode(str);
      return list.cast<Map<String, dynamic>>();
    } catch (e) {
      debugPrint('⚠️ Failed to parse event queue: $e');
      return [];
    }
  }

  Future<void> _saveEventQueue(List<Map<String, dynamic>> queue) async {
    await _prefs.setString(_keyEventQueue, jsonEncode(queue));
  }
}
