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;

  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>;
  }

  Future<void> saveInstallId(String installId) async {
    await _prefs.setString(_keyInstallId, 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);
  }

  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);
  }

  Future<void> clearUserData() async {
    if (!_isInitialized) {
      await init();
    }
    await _prefs.remove(_keyEventQueue);
    debugPrint('TelemetryStorage: cleared user telemetry data');
  }

  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));
  }
}
